I have a section of code that contains a dropdown and 3 readonly input fields. The input fields are populated using javascript, this works fine on it's own using the below code -
$(document).on('change', '.unit', function(e) {
//Getting Value
var role = $('.unit option:selected').data('role');
var power = $('.unit option:selected').data('power');
var type = $('.unit option:selected').data('type');
//Setting Value
$(".role").val(role);
$(".power").val(power);
$(".type").val(type);
});
I am wanting to clone the element using this code -
//define template
var template = $('.duplicate-sections .form-section:first').clone();
//define counter
var sectionsCount = 1;
//add new section
$('body').on('click', '.addsection', function() {
//increment
sectionsCount++;
//loop through each input
var section = template.clone(true, true).find(':input').each(function(){
//set id to store the updated section number
var newId = this.id + sectionsCount;
//update for label
$(this).prev().attr('for', newId);
//update id
this.id = newId;
}).end()
//inject new section
.appendTo('.duplicate-sections');
return false;
});
//remove section
$('.duplicate-sections').on('click', '.remove', function() {
//fade out section
$(this).closest('.form-section').fadeOut(300, function(){
$(this).closest('.form-section').empty();
});
return false;
});
The cloning process works and the dropdown and the inputs are cloned. However when populating the cloned input fields it uses the values from the parent not the clone.
My html is -
<div class="duplicate-sections">
<div class="form-section">
<div class="form-group row">
<label for="inputFirstName" class="col-form-label col-sm-3 text-left text-sm-right">Unit Type</label>
<div class="col-sm-3">
<select name="unit" id="unit" class="form-control unit"><option value="">Select</option><option
data-role="HQ" data-power="4" data-type="Company Commander" value="1">Ehrwig Arellano</option>
<option data-role="HQ" data-power="6" data-type="Company Commander" value="2">Ehrwig
Arellano</option>
<option data-role="HQ" data-power="2" data-type="Tempestor Prime" value="3">Tempestor Prime</option>
</select></div>
<div class="col-sm-2 increment_controls">
<input type="text" id="role" name="role" class="form-control role" readonly placeholder="Role">
</div>
<div class="col-sm-1 increment_controls">
<input type="text" id="power" name="power" class="form-control power" readonly placeholder="PL">
</div>
<div class="col-sm-3 increment_controls">
<input type="text" id="type" name="type" class="form-control type" readonly placeholder="Type">
</div>
</div>
<label for="inputFirstName" class="col-form-label col-sm-3 text-left text-sm-right">
</label><input class="remove col-sm-9" type="button" value="Remove Unit"></input>
</div>
</div>
<label for="inputFirstName" class="col-form-label col-sm-3 text-left text-sm-right"></label>
<input class="addsection col-sm-9" type="button" value="Add Unit"></input>
The whole thing can be found here - JSFiddle
You need to update change event handler script for Unit as here you need to update input fields from the relevant form section only and not for all input fields.
see below code
$(document).on('change', '.unit', function(e) {
//Getting Value
var $option = $(this).find('option:selected');
var role = $option.data('role');
var power = $option.data('power');
var type = $option.data('type');
//Setting Value
var $parent = $(this).closest('.form-section');
$parent.find(".role").val(role);
$parent.find(".power").val(power);
$parent.find(".type").val(type);
});
Demo JSFiddle
Related
Hi I have the following code for appending comboboxes when button is clicked.
I want to check if the value is selected in any previous combobox if it is selected then alert "value is already selected".
For example, I have 5 comboboxes appended and the value in each combobox should be different from each other by traversing each value in the comboboxes:
<div class="custom-control custom-checkbox">
<input type="checkbox" class="itemRow custom-control-input" id="itemRow_1">
<label class="custom-control-label" for="itemRow_1"></label>
</div>
<div class="form-group has-success">
<select name="proid[]" class="form-control" id="proid_1" required="required">
</select>
</div>
<div class="form-group has-success">
<button type="button" name="addbtn" id="addbtn" class="btn btn-success">Add Product</button>
</div>
JQUERY CODE
var count = $(".itemRow").length;
$(document).on('click', '#addbtn', function() {
count++;
var productcombo='';
productcombo += '<tr>';
productcombo +='<td><input type="checkbox" class="custom-control-input itemRow" id="itemRow_'+count+'"> <label class="custom-control-label" for="itemRow_'+count+'"></label> </td>';
productcombo +='<td><select name="proid[]" class="form-control" id="proid_'+count+'" required="required"> </select></td>';
productcombo += '</tr>';
$('#products').append(productcombo);
});
$("#proid_"+count).change(function()
{
var id = $(this).find(":selected").val();
// code here to compare each value
if(value found in previous comboboxes)
{
alert("Already Selected");
}
});
You can set an array variable and when user select a value of combobox, push the value in it.
var selectedVals = [];
$("#proid_"+count).change(function() {
var id = $(this).find(":selected").val();
// code here to compare each value
if(selectedVals.includes(id)) {
alert("Already Selected");
} else {
selectedVals.push(id);
}
});
I'm building this form were the user can add input field dynamically by clicking the + sign.
Then the user can remove the previously added input by clicking the - sign.
My problem is when the user removes one field, all fields are removed. I believe it depends on the position of the .field_wrapper.
I've moved the .field_wrapper to various positions but nothing seems to work. Either way the previously added input is not removed or all inputs are removed.
Can someone advise me on what I'm missing.
here is a link to a fiddle
$(document).ready(function() {
var max_fields = 10;
var add_input_button = $('.add_input_button');
var field_wrapper = $('.field_wrapper');
var new_field_html = '<input name="title[]" class="form-control form-item type="text" value="" data-label="title" />-';
var input_count = 1;
//add inputs
$(add_input_button).click(function() {
if (input_count < max_fields) {
input_count++;
$(field_wrapper).append(new_field_html);
}
});
//remove_input
$(field_wrapper).on('click', '.remove_input_button', function(e) {
e.preventDefault();
$(this).parent('div').remove();
input_count--;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-horizontal">
<div class="row field_wrapper">
<label class="col-md-offset-1 col-sm-3 control-label" for="title">Title</label>
<div class="col-md-6 col-sm-9 col-10">
<input id="title" class="form-control form-item required" name="input_title[]" type="text" value="" data-label="title" />
+
</div>
</div>
</form>
The reason is because the parent('div') from the remove button is the div which holds all the content. The simple way to fix this would be to wrap the new input and remove link in its own div.
Also note that add_input_button and field_wrapper already contain jQuery objects, so you don't need to wrap them again. Try this:
$(document).ready(function() {
var max_fields = 10;
var $add_input_button = $('.add_input_button');
var $field_wrapper = $('.field_wrapper');
var new_field_html = '<div><input name="title[]" class="form-control form-item type="text" value="" data-label="title" />-</div>';
var input_count = 1;
//add inputs
$add_input_button.click(function() {
if (input_count < max_fields) {
input_count++;
$field_wrapper.append(new_field_html);
}
});
//remove_input
$field_wrapper.on('click', '.remove_input_button', function(e) {
e.preventDefault();
$(this).parent('div').remove();
input_count--;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-horizontal">
<div class="row field_wrapper">
<label class="col-md-offset-1 col-sm-3 control-label" for="title">Title</label>
<div class="col-md-6 col-sm-9 col-10">
<input id="title" class="form-control form-item required" name="input_title[]" type="text" value="" data-label="title" />
+
</div>
</div>
</form>
I've the problem with div id in script. I just want to know how to control div id for using function id in another script. Here's my form:
<div class="container">
<div class="row">
<div class="col-md-7 field_wrapper">
<div data-role="dynamic-fields">
<div class="form-inline">
<div class="form-group" id="txtboxToFilter">
<label for="nip">NIP:</label>
<input type="text" class="form-control" id="UserName" onkeyup="checkname();" placeholder="Masukkan NIP" required/>
</div>
<div class="form-group">
<i class='fa fa-fw fa-plus'></i>
</div>
<span id="name_status"></span>
</div>
</div>
</div>
</div>
And here's my script:
$(document).ready(function(){
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div data-role="dynamic-fields"><div class="form-inline"><div class="form-group" id="txtboxToFilter"><label for="nip">NIP:</label> <input type="text" class="form-control" id="UserName" onkeyup="checkname();" placeholder="Masukkan NIP" required/></div><div class="form-group"><label for="jabatan">Jabatan:</label><select class="form-control" id="jabatan" name="jeniskejadian" required><option value=""></option><option value="SMC / KAKANSAR">SMC / KAKANSAR</option><option value="STAFF OPERASI / KASIOPS">STAFF OPERASI / KASIOPS</option><option value="OSC / KORPOS">OSC / KORPOS</option><option value="DANTIM">DANTIM</option><option value="RESCUER">RESCUER</option><option value="STAFF KOMUNIKASI">STAFF KOMUNIKASI</option><option value="HUMAS">HUMAS</option><option value="STAFF ADMINLOG">STAFF ADMINLOG</option></select></div><div class="form-group"><i class="fa fa-fw fa-minus"></i></div><span id="name_status"></span></div></div>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
function checkname()
{
var name=document.getElementById( "UserName" ).value;
if(name)
{
$.ajax({
type: 'post',
url: 'checkdata.php',
data: {
user_name:name,
},
success: function (response) {
$( '#name_status' ).html(response);
if(response=="OK")
{
return true;
}
else
{
return false;
}
}
});
}
else
{
$( '#name_status' ).html("");
return false;
}
}
For the first time in
<div class="form-group" id="txtboxToFilter">
<label for="nip">NIP:</label>
<input type="text" class="form-control" id="UserName" onkeyup="checkname();" placeholder="Masukkan NIP" required/>
</div>
It can be used to using function checkname(), but if I would to click in
<div class="form-group">
<i class='fa fa-fw fa-plus'></i>
</div>
for adding the same input type text with function of my script $(addButton)
var fieldHTML = '<div data-role="dynamic-fields"><div class="form-inline"><div class="form-group" id="txtboxToFilter"><label for="nip">NIP:</label> <input type="text" class="form-control" id="UserName" onkeyup="checkname();" placeholder="Masukkan NIP" required/></div><div class="form-group"><i class="fa fa-fw fa-minus"></i></div><span id="name_status"></span></div></div>';
but the result is that var fieldHTML couldn't use function onkeyup checkname(). Please help me...
You should pass a reference of the element on which the inline event listener is attached to. You need to pass the this reference to the function and use the this reference to get the element.
Change you functions by adding this.
e.g.
<input type="text" class="form-control" id="UserName" onkeyup="checkname(this);" placeholder="Masukkan NIP" required/>
Also, for fieldHTML
var fieldHTML = '<div data-role="dynamic-fields"><div class="form-inline"><div class="form-group" id="txtboxToFilter"><label for="nip">NIP:</label>
<input type="text" class="form-control" id="UserName" onkeyup="checkname(this);" placeholder="Masukkan NIP" required/></div><div class="form-group"><label for="jabatan">Jabatan:</label><select class="form-control" id="jabatan" name="jeniskejadian" required><option value=""></option><option value="SMC / KAKANSAR">SMC / KAKANSAR</option><option value="STAFF OPERASI / KASIOPS">STAFF OPERASI / KASIOPS</option><option value="OSC / KORPOS">OSC / KORPOS</option><option value="DANTIM">DANTIM</option><option value="RESCUER">RESCUER</option><option value="STAFF KOMUNIKASI">STAFF KOMUNIKASI</option><option value="HUMAS">HUMAS</option><option value="STAFF ADMINLOG">STAFF ADMINLOG</option></select></div><div class="form-group"><i class="fa fa-fw fa-minus"></i></div><span id="name_status"></span></div></div>';
Function checkname(element) as :
variable element contains the element this is being used. You can access the element by using element variable.
function checkname(element)
{
var name= element.value;
console.log('Checkname '+name);
}
Have problem to display select on change attribute id.
PHP:
<form action="" class="form-inline">
<div class="form-group">
<select name="kategorijos" id="kategorijos" class="category form-control" onchange="fetch_select_category(this.value);">
<option value=""></option>
FOREACH
</select>
</div>
<div class="form-group">
<fieldset disabled>
<select id="disabledSelect" name="subcategories" class="subcategory form-control" onchange="fetch_select_product(this.value);" required>
<option value="" disabled selected>Select Subcategory</option>
</select>
</fieldset>
</div>
<div class="form-group">
<td><input type="text" name="gramai" class="form-control" value=""></td>
</div>
<div class="form-group" id="kalb">
<input type='text' name='1[]' value="-" disabled>
<input type='text' name='12[]' value="-" disabled>
<input type='text' name='123[]' value="-" disabled>
<input type='text' name='1234[]' value="-" disabled>
</div>
</form>
My jquery code:
$("select").on('change', function() {
var status = $('select').attr('id');
alert(status);
});
var categoryId = 0;
var category = 0;
var product = 0;
var disableId = 0;
$("#add").click(function () {
categoryId = categoryId + 1;
category = category + 1;
product = product + 1;
disableId = disableId + 1;
$("#item").append('<div class="col-xs-12"><form action=""
class="form-inline"><div class="form-group"><select name="kategorijos"
**....... same code as above (php)**
});
When I select the first row it alerts value. But then I add new row with add button, and then change second select the alert don't work, and I don't get the select id. Where can be the problem? Maybe it doesn't work with append html ?
You need to use event delegation for dynamically generated element and also use this instead of 'select' to get the id of dropdown.
$(document).on('change', 'select', function() {
var status = $(this).attr('id');
alert(status);
});
<div class="form-inline">
<div class="form-group col-lg-4">
<label>Select Item:</label>
<div id="field1">
<select class="form-control" name="item_1">
<?php if($item !=0){foreach ($item as $list_item){?>
<option value="<?php echo $list_item['item'];?>">
<?php echo $list_item[ 'item'];?>
</option>
<?php }}else {?>
<option value="">No Items Available</option>
<?php }?>
</select>
</div>
</div>
<div class="form-group col-lg-2">
<label>Quantity:</label>
<div id="field2">
<input type="number" min="1" class="form-control input-md" name="quantity_1" />
</div>
</div>
<div class="form-group col-lg-3">
<label>Cost(per piece):</label>
<div id="field3">
<input type="number" min="1" class="form-control input-md" name="cost_1" />
</div>
</div>
<div class="form-group col-lg-3" style="margin-top:25px">
<div id="field4">
<button id="addmore" onclick="add();" class="btn add-more" type="button">+</button>
</div>
</div>
</div>
I have these three fields('item, quantity and cost') and these three fields are added incrementally on clicking + button but i am having removing these buttons on - click.
I simply need these three input fields to be added at one click and remove these fields on one click as well. also these fields name should be incremented.
<script>
function add() {
i++;
var div1 = document.createElement('div');
div1.innerHTML = '<select class="form-control" name="item_' + i + '"> <option value=""></option></select>';
document.getElementById('field1').appendChild(div1);
var div2 = document.createElement('div');
div2.innerHTML = '<input type="number" min="1" class="form-control input-md" name="quantity_' + i + '" />';
document.getElementById('field2').appendChild(div2);
var div3 = document.createElement('div');
div3.innerHTML = '<input type="number" min="1" class="form-control input-md" name="cost_' + i + '" />';
document.getElementById('field3').appendChild(div3);
var div4 = document.createElement('div');
div4.innerHTML = '<button id="remove" onclick="remove_btn(this)" class="btn remove" type="button">-</button>';
document.getElementById('field4').appendChild(div4);
}
</script>
There are several issues:
Avoid putting blobs of HTML in your javascript, put your HTML in the HTML file.
Avoid IDs, particularly when they will certainly be duplicated. Duplicate IDs are illegal. Only the first one can be found with a lookup.
Avoid concatenating together strings of text to generate your HTML. It is a too easy to make a mistake and put an XSS vulnerability in your code that way.
(function($) {
"use strict";
var itemTemplate = $('.example-template').detach(),
editArea = $('.edit-area'),
itemNumber = 1;
$(document).on('click', '.edit-area .add', function(event) {
var item = itemTemplate.clone();
item.find('[name]').attr('name', function() {
return $(this).attr('name') + '_' + itemNumber;
});
++itemNumber;
item.appendTo(editArea);
});
$(document).on('click', '.edit-area .rem', function(event) {
editArea.children('.example-template').last().remove();
});
$(document).on('click', '.edit-area .del', function(event) {
var target = $(event.target),
row = target.closest('.example-template');
row.remove();
});
}(jQuery));
.hidden { display: none; }
.formfield { float: left; }
.example-template { clear: left; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hidden">
<div class="example-template">
<div class="formfield"><input placeholder="Name" name="name"></div>
<div class="formfield"><input placeholder="Addr" name="addr"></div>
<div class="formfield"><input placeholder="Post" name="post"></div>
<div class="formfield"><button class="del">-</button></div>
</div>
</div>
<div class="edit-area">
<div class="controls">
<button class="add">+</button>
<button class="rem">-</button>
</div>
</div>
This works by first grabbing the row template out of the hidden div element, and storing it in a variable. Each time it needs to make a new row, it clones the template and updates it. It updates it by adjusting the name element as required, appending "_" and a number. Once it has customized this copy of the template, it appends it to the edit area.
You can remove elements with a reference to the parent using similar syntax with the following:
var childElement = document.getElementById("myChildElement");
document.getElementById("myElement").removeChild(childElement);
Similar to what is described here: http://www.w3schools.com/js/js_htmldom_nodes.asp
Also, consider a toggle on the CSS style property: "display: none;"