Lakmal Premaratne Lakmal Premaratne - 24 days ago 9
jQuery Question

assign value to a text box from jQuery

In the form, I have put a textbox and a button as:

<input type="text" class="form-control" id="txtCustomerId" placeholder="Customer ID">
<span class="input-group-btn">
<button class="btn btn-secondary" type="button" data-toggle="modal" data-target="#LovCustomer"><i class="fa fa-list"></i></button>
</span>


when this button is pressed, a modal form (bootstrap) is popped up. I have placed a button on the modal form as:

<td><button id="LSSL" value="LSSL" class="btn btn-info btn-xs"><i class="fa fa-caret-right"></i></button></td>


I have below jQuery in
<head>
:

$(function(){
$('#LSSL').click(function(){
$('#txtCustomerId').val($(this).val());
});
});


My requirement is to obtain the value of the button being pressed (in the modal form) and assign it to the txtCustomerId of the parent form. But when I press the button, page gets refreshed and the text filed is blank (since it is refreshed).

I think the value is assigned but since the page is refreshed, assigned value vanishes.

I would like to know either to stop the page refresh or any other way of getting this achieved.

Thanks in advance.

Below is my
<head>
section for your reference:

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" media="screen" href="http://tarruda.github.com/bootstrap-datetimepicker/assets/css/bootstrap-datetimepicker.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(function(){
$('button').click(function(e){
e.preventDefault();
var value = $(this).val();
$('#txtCustomerId').val(value);
});
});
</script>
</head>

Answer

Your button should be like this,

<td><button type="button" id="LSSL" value="LSSL" class="btn btn-info btn-xs"><i class="fa fa-caret-right"></i></button></td>

And in Js part, you can do preventDefault(),

$(function(){
   $('#LSSL').click(function(e){
       e.preventDefault();
       var value = $(this).attr('value');
       $('#txtCustomerId').val(value);
   });
});

//You can also use $(document).ready(function(){}) as well.
$(document).ready(function(){
    $('#LSSL').click(function(e){
       e.preventDefault();
       var value = $(this).attr('value');
       $('#txtCustomerId').val(value);
   });
});
Comments