$('.class').click() doesn't work - javascript

I've made a jQuery function which execute when a button which contains the class button-trash is clicked. The problem is that there is no reaction when I click on the button but the alert in the $(document).ready(function() works.
HTML
<div id="div_flotte">
<div class="div_avion" style="display:none;">
<div class="panel panel-default">
<div class="panel-heading">
<div class="form-inline">
<div class="input-group" style="width:200px">
<span class="input-group-addon" id="basic-addon1">F-BEN</span>
<input type="text" name="avions[][immat]" class="form-control" placeholder="Ex : 49" >
</div>
<div class="input-group" style="float:right;">
<button class="btn btn-danger button-trash" type="button" name="button"><i class="fa fa-trash"></i></button>
</div>
</div>
</div>
<div class="panel-body">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">Marque</span>
<input type="text" name="avions[][marque]" class="form-control" placeholder="Ex : Airbus" >
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">Modèle</span>
<input type="text" name="avions[][modele]" class="form-control" placeholder="Ex : 737" >
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">IATA</span>
<input type="text" name="avions[][iata]" class="form-control" placeholder="Ex : 738" >
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">Type de vol</span>
<select name="avions[][type]" class="form-control-inline">
<?php
foreach ($types_vol_avion as $cle => $value) {
echo '<option value="'.$cle.'">'.$value.'</option>';
}
?>
</select>
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">Transport</span>
<select name="avions[][activite]" class="form-control-inline">
<?php
foreach ($Activite_avion as $cle => $value) {
echo '<option value="'.$cle.'">'.$value.'</option>';
}
?>
</select>
</div>
</div>
</div>
</div>
</div>
JS
$(document).ready(function(){
$('.button-trash').click(function(){
alert("test");
});
alert("test");
});
EDIT :
The div .div_avionis created dynamicly by this function :
function AddAvion()
{
$( ".div_avion" ).eq(0).clone().attr({id:'div_avion'+($(".div_avion").length+1), style:'display:visible;'}).css('display', 'visible').appendTo( "#div_flotte" );
}

All right. Since you are creating a dynamic element, you can add your event like this:
$(document).on('click', '.button-trash', function() {
alert('hello');
});
Hope this helps.

If Dynamically produced button, then you should use the on() method
<script>
$(document).ready(function(){
$('.input-group').on('click','.button-trash', function(){
alert ('it is working');
alert("test");
});
alert("test");
});
</script>

Related

how can ı access all inputs in form

I found this code in https://codepen.io/pkbhuiyan/pen/VaVNQd . I passed "id" to form tag and I am trying to access all inputs in form tag but it does not work.
jQuery:
$(document).ready(function () {
jQuery(function ($) {
var $inputs = $( "#contact_form :input" ).prop("disabled", true);;
$("#edit_btn").click(function () {
$("#submit_btn").show(0);
$("#edit_btn").hide(0);
$inputs.prop("disabled", false);
});
$("#submit_btn").click(function () {
$inputs.prop("disabled", true);
$("#submit_btn").hide(0);
$("#edit_btn").show(0);
});
});
});
HTML:
<div id="kursiyerprofili">
<form action="/" method="post">
<div class="main">
<div class="container-fluid">
<div class="row">
<div class="contact_form col-sm-10 col-md-10">
<form name="contact_form" id="contact_form" class="contact_form" method="post">
<div class="row">
<div class="col-sm-5 col-md-5">
<label>İSİM</label>
<input name="name" id="student-name" class="form-control" type="text" value="" />
</div>
<div class="col-sm-5 col-md-5">
<label>SOYİSİM</label>
<input name="surname" id="student-surname" class="form-control" type="text" value="" />
</div>
<div class=" pull-right profile-edit-button ">
<a id="edit_btn" class="btn btn-warning" name="submit">Profili Düzenle</a>
<a id="submit_btn" class="btn btn-warning" name="submit">Değişiklikleri Kaydet</a>
<!--<span id="notice" class="alert alert-warning alert-dismissable hidden" style="margin-left:20px;"></span>-->
</div>
</div>
</form>
</div> <!--contact-form-->
</div> <!--row-->
</div> <!--container-fluid-->
</div> <!--main-->
</form>
</div>
If my form is like below:
<form id="myForm" action="/action_page.php"></form>
I can access all elements like bwlow:
document.getElementById("myForm").elements
The jQuery way:
$("form").each(function(){
$(this).find(':input')
});

how to change bootstrap card-header value with java script?

I have a ejs(html) file, and There is a div class called "card".
What I want to do is that, if I click the button("Click me") then,
card-header(header1) has to be changed(before --> after) with colored back-ground.
However when I clicked the button, only the back-ground color was changed (excluding the header). need your help.
function save() {
var x = document.getElementById("header1");
x.style.backgroundColor="#cfe8f9";
x.setAttribute("value", "After");
}
<div class="col-sm-6">
<div class="card">
<div class="card-header" id="header1" style="font-weight:bold;">before</div>
<div class="card-body">
<form action="" method="POST">
<input type="hidden" id="input_flag" value="">
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">noID</span>
</div>
<input type="text" id="notiSeq_1" name="notiSeq_1" class="form-control" value="" style="background-color:#FFFFFF">
<div class="input-group-append">
<span class="input-group-text">
<i class="fa fa-sort-numeric-asc"></i>
</span>
...
...
...
<button type="button" class="btn btn-primary" onclick ="save()">Click me</button>
</div> //end of col-sm-6
Update the innerHTML
function save() {
var x = document.getElementById("header1");
x.style.backgroundColor="#cfe8f9";
x.innerHTML = "After";
}
<div class="col-sm-6">
<div class="card">
<div class="card-header" id="header1" style="font-weight:bold;">before</div>
<div class="card-body">
<form action="" method="POST">
<input type="hidden" id="input_flag" value="">
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">noID</span>
</div>
<input type="text" id="notiSeq_1" name="notiSeq_1" class="form-control" value="" style="background-color:#FFFFFF">
<div class="input-group-append">
<span class="input-group-text">
<i class="fa fa-sort-numeric-asc"></i>
</span>
...
...
...
<button type="button" class="btn btn-primary" onclick ="save()">Click me</button>
</div> //end of col-sm-6

clone existing div with Jquery

i have an issue. How can i clone an existing div with jquery?
[Image]1
<div class="modal-body">
<div class="row">
<div class="col-md-5 text-center">
<b>Número Factura</b>
<input type="number" class="form-control" id="numero"><br/>
</div>
<div class="col-md-2 text-center">
-o-
</div>
<div class="col-md-5 text-center">
<b>Número Remisión</b>
<input type="number" class="form-control" id="remision"><br/>
</div>
<div class="col-md-12">
<b>NIT:</b>
<?php $consulta = mysqli_query($conexion, "SELECT * FROM proveedores");
$resultado = mysqli_fetch_all($consulta, MYSQLI_ASSOC); ?>
<select class="form-control" id="proveedor">
<?php foreach($resultado as $r): ?>
<option value="<?php echo $r['nit']; ?>"><?php echo $r['nombre']; ?></option>
<?php endforeach; ?>
</select><br/>
</div>
<div class="col-md-2">
<input type="number" class="form-control" id="productos" value="1">
</div>
<div class="col-md-2">
<button type="button" class="btn btn-success agregar_producto" name="agregar_producto">
<i class="fas fa-user-plus" style="color: white"></i>
</button>
</div>
</div>
<br/>
<div id="contenido" class="row text-center">
<div class="col-md-4">
<b>Producto</b>
<?php $consulta = mysqli_query($conexion, "SELECT * FROM productos");
$resultado = mysqli_fetch_all($consulta, MYSQLI_ASSOC); ?>
<select class="form-control" id="producto">
<?php foreach($resultado as $r): ?>
<option value="<?php echo $r['id']; ?>"><?php echo $r['descripcion']; ?></option>
<?php endforeach; ?>
</select><br/>
</div>
<div class="col-md-4">
<b>Cantidad</b>
<input type="number" class="form-control" id="cantidad"><br/>
</div>
<div class="col-md-4">
<b>Precio</b>
<input type="number" class="form-control" id="precio"><br/>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success crear" name="crear">Agregar Factura</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Regresar</button>
</div>
I need to clone the div with id="contenido" when someone press the button with class="agregar_producto".
How can i solve it?
[Example]2
Is it possible? i need only an example to solve my problem.
Thx you! <3
EDIT: If a clone this inputs how can i change ids/class to this inputs?
Hi Please check below code:
<html>
<head>
<title>Sample HTML</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body bgcolor=white>
<div id="contenido" class="row text-center">
<div class="col-md-4">
<b>Producto</b>
<select class="form-control" id="producto">
<option value="product1">product1</option>
<option value="product2">product2</option>
<option value="product3">product3</option>
<option value="product4">product4</option>
<option value="product5">product5</option>
<option value="product6">product6</option>
</select><br/>
</div>
<div class="col-md-4">
<b>Cantidad</b>
<input type="number" class="form-control" id="cantidad"><br/>
</div>
<div class="col-md-4">
<b>Precio</b>
<input type="number" class="form-control" id="precio"><br/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn agregar_producto" name="crear">Agregar Producto</button>
</div>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$(".agregar_producto").on('click', function() {
var $contenido = $("#contenido:last");
var $clone = $contenido.clone();
$clone.find('input').val('');
$contenido.after($clone);
});
});
</script>
</body>
</html>
1.Id need to be unique per element so convert id="contenido" to class="contenido"
2.Use .clone()
$('.agregar_producto').on('click', function(){
var clone = $( ".contenido:first" ).clone();
$(clone).attr('id','changedId'); //change cloned element id attribute
$(clone).find('select').attr('id','changedId1'); //change cloned element children attribute also
$(clone).insertAfter( ".contenido:last" );
});
Note:- add selector(class or id) of the element after which you want to append the clone.
Reference:-
.insertAfter()
Working snippet:-
$('.agregar_producto').on('click', function(){
var clone = $( ".contenido:first" ).clone();
$(clone).attr('id','changedId'); //change cloned element id attribute
$(clone).find('select').attr('id','changedId1'); //change cloned element children attribute also
$(clone).insertAfter( ".contenido:last" );
});
#changedId{
background:yellow;
}
#changedId1{
font-size:20px;
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-body">
<div class="row">
<div class="col-md-5 text-center">
<b>Número Factura</b>
<input type="number" class="form-control" id="numero"><br/>
</div>
<div class="col-md-2 text-center">
-o-
</div>
<div class="col-md-5 text-center">
<b>Número Remisión</b>
<input type="number" class="form-control" id="remision"><br/>
</div>
<div class="col-md-12">
<b>NIT:</b>
<?php $consulta = mysqli_query($conexion, "SELECT * FROM proveedores");
$resultado = mysqli_fetch_all($consulta, MYSQLI_ASSOC); ?>
<select class="form-control" id="proveedor">
<?php foreach($resultado as $r): ?>
<option value="<?php echo $r['nit']; ?>"><?php echo $r['nombre']; ?></option>
<?php endforeach; ?>
</select><br/>
</div>
<div class="col-md-2">
<input type="number" class="form-control" id="productos" value="1">
</div>
<div class="col-md-2">
<button type="button" class="btn btn-success agregar_producto" name="agregar_producto">
<i class="fas fa-user-plus" style="color: black">Click me to append Clone</i>
</button>
</div>
</div>
<br/>
<div class="contenido" class="row text-center">
<div class="col-md-4">
<b>Producto</b>
<select class="form-control" id="producto">
<option value="1">1</option>
<option value="1">2</option>
<option value="1">3</option>
<option value="1">4</option>
<option value="1">5</option>
</select><br/>
</div>
<div class="col-md-4">
<b>Cantidad</b>
<input type="number" class="form-control" id="cantidad"><br/>
</div>
<div class="col-md-4">
<b>Precio</b>
<input type="number" class="form-control" id="precio"><br/>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success crear" name="crear">Agregar Factura</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Regresar</button>
</div>
.clone() method create a deep copy of the set of matched elements. And .appendTo( ) to append the cloned element.
$('.agregar_producto').on('click', function(){
$( "#contenido" ).clone().appendTo( "body" );
});
$('.agregar_producto').click(function(){
$( "#contenido" ).clone().appendTo( "body" );
});
you can change the above to append the clone under specific elements.
You could easily do the following.
<div id="div1">
<p>
Content in DIV1
</p>
</div>
<div id="tgt">
</div>
jQuery snippet would be as follows.
$(document).ready(function(){
var div1 = $("#div1").clone(); //Clone the element. Assigned to the JS variable div1
div1.attr("id", "div1clone"); //Modify the necessary properties using $(element).attr()
$("#tgt").append(div1); //Append the content to where ever desired
});
This is just a very rusty sample. Check this fiddle out to see this in action.

Dynamic multiselect feature

I am creating the fields dynamically in HTML using this JS, and in multiselect I'm using bootstrap multiselect here is the code https://bootsnipp.com/snippets/Ekd8P when I click on the add more button it creates the form dynamically.
js code for creating a form dynamically :
$(function() {
// Remove button
$(document).on(
'click',
'[data-role="dynamic-fields"] > .form-horizontal [data-role="remove"]',
function(e) {
e.preventDefault();
$(this).closest('.form-horizontal').remove();
}
);
// Add button
var i = 1;
$(document).on(
'click',
'[data-role="dynamic-fields"] > .form-horizontal [data-role="add"]',
function(e) {
e.preventDefault();
var container = $(this).closest('[data-role="dynamic-fields"]');
new_field_group = container.children().filter('.form-horizontal:first-child').clone();
new_field_group.find('input').each(function() {
if (this.name == 'tags[0]') {
$(this).tagsinput('destroy');
$(this).tagsinput('removeAll');
this.name = this.name.replace('[0]', '[' + i + ']');
var new_container = $(this).closest('[class="form-group"]');
new_container.find(".bootstrap-tagsinput:first").remove();
} else {
$(this).val('');
}
});
new_field_group.find('select').each(function() {
if (this.name == 'addons[0]') {
$(this).multiselect('rebuild');
this.name = this.name.replace('[0]', '[' + i + ']');
var new_container = $(this).closest('[class="multiselect-native-select"]');
new_container.find(".multiselect-native-select > .multi").remove();
} else {
$(this).val('');
}
});
i += 1;
container.append(new_field_group);
}
);
});
and html code for form elements:
<form action="" method="post" novalidate="novalidate" enctype="multipart/form-data">
{{ csrf_field() }}
<div data-role="dynamic-fields">
<div class="form-horizontal">
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Enter Dish Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="Name1" name="Name[]" required data-rule-minlength="2">
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Enter Dish Price</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="Price" name="Price[]" required data-rule-minlength="2">
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Select Food Type</label>
<div class="col-sm-8">
<select id="select1" class="form-control" name="select[]" required>
#foreach($types as $type)
<option value="{{$loop->iteration}}">{{$type->food_type_name}}</option>
#endforeach
</select>
<p class="help-block" data-toggle="tooltip" data-placement="bottom" title="xyz"><i class="md md-info"></i></p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Dish Description</label>
<div class="col-sm-8">
<textarea name="Description[]" id="field-value" class="form-control" rows="1"></textarea>
</div>
</div>
</div>
<div class="col-sm-4 contacts">
<div class="form-group">
<label class="col-sm-3" for="rolename">Add Addons</label>
<div class="col-sm-8">
<select id="dates-field2" class="multiselect-ak form-control" name="addons[0]" id="trigger3" data-role="multiselect" multiple="multiple">
#foreach($addons as $addon)
<option value="{{$addon->addonid}}">{{$addon->addon_name}}</option>
#endforeach
</select>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Enter Tags</label>
<div class="col-sm-8">
<input type="text" value="" name="tags[0]" class="form-control" data-role="tagsinput" placeholder="e.g. spicy, healthy" />
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<div class="col-sm-4">
<div class="checkbox checkbox-styled">
<label><em>Half Plate Price</em>
<input type="checkbox" value="" class="trigger2" id="trigger2" name="question">
</label>
</div>
</div>
<div class="col-sm-4">
<div id="hidden_fields2" class="hidden_fields2" style="display:none;">
<input type="text" id="hidden_field2" name="Price2[]" placeholder="Please Enter" class="form-control">
</div>
</div>
</div>
<div class="col-sm-4">
<div class="col-sm-5">
<div class="checkbox checkbox-styled">
<label><em>Quarter Plate Price</em>
<input type="checkbox" value="" class="trigger" id="trigger" name="question">
</label>
</div>
</div>
<div class="col-sm-4">
<div id="hidden_fields" class="hidden_fields" style="display:none;">
<input type="text" id="hidden_field" name="Price3[]" placeholder="Please Enter" class="form-control">
</div>
</div>
</div>
</div>
<br>
<button class="btn btn-delete" data-toggle="tooltip" data-placement="bottom" title="Delete Field" data-role="remove">
Delete Item
</button>
<button class="btn ink-reaction btn-raised btn-primary" data-toggle="tooltip" data-placement="bottom" title="Add More Field" data-role="add">
Add More Items
</button>
</div>
<!-- /div.form-inline -->
</div>
<!-- /div[data-role="dynamic-fields"] -->
<div class="form-group">
<button type="submit" name="submit" href="#" class="btn ink-reaction btn-raised btn-primary" style="margin-top: -62px;margin-left: 160px;">Submit Items</button>
</div>
<!--end .form-group -->
</form>
The issue is that when I click on the add more item it reflects the multiselect dropdown twice as you see in this image.
I want that if I click on the add more item button it restates the multiselect dropdown as in the first state.
see this jsfiddle.net/akshaycic/svv742r7/7 it will clear all your doubt. on click plus button it is not reflect to "none selected" state it will remain in its initial state.
Any leads would be helpful. Thank you in advance.

Multiple two inputs and the inputs generated dynamically by jQuery

I have this form and this is my layout:
I want when the user enters the quantity the total input = qty*price.
My view
<?php $form=array('id'=>'myform');?>
<?php echo form_open('Order/submit',$form);?>
<div class="panel panel-default">
<div class="panel-heading">Customer Details</div>
<div class="panel-body">
<div class="col-xs-3">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="customer_name">
<?php foreach ($customerdata as $c):
echo "<option value ='$c->c_id'>" . $c->c_name . "</option>";
endforeach;
?>
</select>
</div>
<div class="col-xs-3">
<input type="text" class="form-control" name="invoice_number" placeholder="Invoice Number"/>
</div>
<div class="col-xs-3">
<input type="text" class="form-control" name="branch" placeholder="Branch"/>
</div>
<div class="col-xs-3">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="payment_term"">
<option value="cash">Cash</option>
<option value="bank">Bank</option>
<option value="other">Other</option>
</select>
</div>
</div><!--customer panel-Body-->
<div class="panel-heading">Invoice Details
</div>
<div class="panel-body">
<div id="education_fields">
<div class="col-sm-3 nopadding">
<div class="form-group">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="select_product[]">
<option></option>
<?php
foreach($order as $row):
echo"<option data-price='$row->p_price' value ='$row->p_id'>".$row->p_name. "</option>";
endforeach;
?>
</select>
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control qty" name="qty[]" value="" placeholder="Quantity">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control price" name="price[]" value="" placeholder="Price">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control total" name="total[]" value="" placeholder="Total">
<div class="input-group-btn">
<button class="btn btn-success" type="button" onclick="education_fields();"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> </button>
</div>
</div>
</div>
</div>
<div class="clear"></div>
</div>
</div>
<div class="panel-footer"><small>Press <span class="glyphicon glyphicon-plus gs"></span> to add another product field :)</small>, <small>Press <span class="glyphicon glyphicon-minus gs"></span> to remove the last product :)</small></div>
</div>
<button type="submit" class="btn btn-primary center-block">Checkout</button>
<?php echo form_close();?>
This is my first jQuery and that used to generate a new row by + button
<script>
var room = 0;
function education_fields() {
room++;
var objTo = document.getElementById('education_fields');
var divtest = document.createElement("div");
divtest.setAttribute("class", "form-group removeclass"+room);
var rdiv = 'removeclass'+room;
var medo='<div class="col-sm-3 nopadding"><div class="form-group"><select class="selectpicker" data-show-subtext="true" data-live-search="true" name="select_product[]"><option></option><?php foreach($order as $row){ ?><option data-price="<?php echo$row->p_price;?>" value ="<?php echo $row->p_id; ?>"><?php echo $row->p_name; ?></option><?php } ?></select></div></div><div class="col-sm-3 nopadding"><div class="form-group"> <input type="text" class="form-control" name="qty[]" value="" placeholder="Quantity"></div></div><div class="col-sm-3 nopadding"><div class="form-group"> <input type="text" class="form-control price" name="price[]" value="" placeholder="Price"></div></div><div class="col-sm-3 nopadding"><div class="form-group"><div class="input-group"> <input class="form-control" name="total[]" placeholder="Total"/><div class="input-group-btn"> <button class="btn btn-danger" type="button" onclick="remove_education_fields('+ room +');"> <span class="glyphicon glyphicon-minus" aria-hidden="true"></span> </button></div></div></div></div><div class="clear"></div>';
divtest.innerHTML = medo;
objTo.appendChild(divtest);
$('select').selectpicker();
}
function remove_education_fields(rid) {
$('.removeclass'+rid).remove();
}
</script>
and this 2nd jQuery used to get product price from from drop-menu attributes and add that into price input.
<script>
function set_price( slc ) {
var price = slc.find(':selected').attr('data-price');
slc.parent().parent().next().next().find('.price').val(price);
}
$('#education_fields').on('change','select.selectpicker',function(){
set_price( $(this) );
});
</script>
var sample = $('#sample').html();
$('#sample').on('click', '.generate', function() {
$('#sample').append(sample);
});
$('#sample').on('change', 'select.selectpicker', function () {
// keyword this is your current select element
var select = $(this);
// each group of inputs share a common .form element, so use that to
// look up for closest parent .form, then down for input[name="price[]"]
// and set the input's value
select.closest('.form').find('[name^=price]').val(
select.find('option:selected').data('price')
// trigger input's keyup event (*)
).keyup();
});
// (*) note: input[type=text]'s onchange event triggers only after it loses focus; we'll use keyup event instead
// create onkeyup event on the qty and price fields
$('#sample').on('keyup', '[name^=qty], [name^=price]', function() {
// get related form
var form = $(this).closest('.form');
// get its related values
var qty = parseInt(form.find('[name^=qty]').val(), 10),
price = parseInt(form.find('[name^=price]').val(), 10);
// ensure only numbers are given
if (!isNaN(qty) && !isNaN(price)) {
// set the total
form.find('[name^=total]').val(qty * price);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sample">
<!-- group all related blocks into a div .form -->
<!-- it makes it easier to reference in your JS -->
<div class="form">
<div class="col-sm-3 nopadding">
<div class="form-group">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="select_product[]">
<option data-price=200 value=1>tes1</option>
<option data-price=218 value=2>tes2</option>
<option data-price=80 value=3>tes3</option>
</select>
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control" name="qty[]" value="" placeholder="Quantity">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control price" name="price[]" value="" placeholder="Price">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control " name="total[]" value="" placeholder="total" readonly>
</div>
</div>
</div>
<button class="generate" type="button">Generate New Form</button>
</div>
Note, that I am lazy instead of doing [name="price[]"], I simply did [name^=price].
Edit changed onchange to keyup.

Categories

Resources