when I click on button in modal then textbox values becomes null or text disappear. how to maintain the text in textbox.
Modal :
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-
dismiss="modal">×</button>
<h4 class="modal-title">Update Country</h4>
</div>
<form action="" method="post">
<div class="modal-body">
<input type="text" id="cn" name="pcountry">
</div>
<div class="modal-body">
<input type="text" id="cph" name="pphone">
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-default"
name="updatecountry">
</div>
</form>
</div>
Jquery Code :
<script>
$(document).ready(function(){
$(".btn").click(function(){
var cphone =$(this).data('cphone');
var cname = $(this).data('cname');
$("#cph").val(cphone);
$("#cn").val(cname);
</script>
Ofcourse the text in your textboxes will disapear when you are putting null value. I'm reading your code and it is totaly not making sense to me. Now I will explain what is your code doing and hope you will understand your mistakes.
$(this)
in your code is refering to the clicked button.
read what jquery's data method doing here and the way you are using it will try to get attribute data-cphone
and data-cname
values from the clicked button and since there are no such attributes var cphone
and var cname
are both null.
Example:
// HTML
<input type="submit" id="my-button" data-cphone="some value" data-cname="some other value">
// JavaScript
// now you will have "some value" inside cphone and "some other value" inside cname
var cphone =$('#my-button').data('cphone');
var cname = $('#my-button').data('cname');
$("#cph").val(cphone);
you are setting the value of your <input>
to nullso
when I click on button in modal then textbox values becomes null or text disappear. how to maintain the text in textbox.
yes my friend this is the expected behaviour.
If you use your code like this:
// now your variables will hold the values of those two inputs
var cphone = $("#cph").val();
var cname = $("#cn").val();
// now for example you can send your values to PHP with AJAX
$.ajax({
method: 'POST',
url: 'path/to/data/processing/script.php',
data: {name: cname, phone: cphone },
success: function(response){
// process your response here
},
error: function(err){
// handle your error here
},
complete: function(){
// clear input values for example
$("#cph").val('');
$("#cn").val('');
}
});
it will work. Good Luck!
EDIT
Check this jsfiddle for another way to get the values of the inputs using the jquery's closest method to find the parent form and then using the find method to get those two inputs