How to put html into js loop - javascript

Today I need help about How can I do a loop with html code and put the (i) value on the input name:
<label>
<input type='radio' class='parts' value='5' /> 5
</label>
<script>
$(function(){
jQuery('.parts').on('click', function(){
var html = '';
for(i=1; i <= $(this).val(); i++ ){
html += "<input type='text' name='cars[i]' /> car number i";
}
$('#result').html(html);
});
});
</script>
<div id='result'></div>
If you dont undertand pls ask.

You can use string concatenation:
html += "<input type='text' name='cars[" + i + "]' /> car number " + i;
$(function(){
jQuery('.parts').on('click', function(){
var html = '';
for(i=1; i <= $(this).val(); i++ ){
html += "<input type='text' name='cars[" + i + "]' /> car number " + i + "<br>";
}
$('#result').html(html);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type='radio' class='parts' value='5' /> 5
</label>
<div id='result'></div>

Related

Generate dynamic li elements depending on how many checkboxes are checked

I am trying to generate li elements for each checkbox that has been checked. It works when there is only one checked, but when I check 2 checkboxes, only the last checkbox and its hidden inputs (hidden inputs used to populate specific values inside the li element) are generated.
Here is the code I use now:
attachPanelListeners : function() {
$('#sc-accordion').bind('click', function(e) {
var items,
target = $(e.target);
if ( target.hasClass('submit-add-to-menu') ) {
var t = $(this).parent().parent(),
checkboxes = t.find('.sc-pagelist li input:checked');
// If no items are checked, bail.
if ( !checkboxes.length )
return false;
var structure;
$(checkboxes).each(function(){
var hidden = $(this).closest('li').find(':hidden');
structure = "<li class='menu-item menu-item-depth-0'>"+
"<div class='menu-item-bar'>"+
"<div class='menu-item-handle ui-sortable-handle'>"+
"<span class='item-title'><span class='menu-item-title'>" + hidden[0].value + "</span></span>"+
"<span class='item-controls'><span class='item-type'>Pagina</span><a href='#' class='item-edit'></a></span>"+
"</div>"+
"</div>"+
"<div class='menu-item-settings sc-clearfix' style='display:none;'>"+
"<p class='description description-wide'>"+
"<label for='edit-menu-title'>Navigatielabel</label>"+
"<input type='text' class='form-control' id='edit-menu-title' value='" + hidden[0].value + "'>"+
"</p>"+
"<fieldset class='field-move hide-if-no-js description description-wide'>"+
"<span class='field-move-visual-label' aria-hidden='true'>Verplaatsen</span>"+
"<button type='button' class='button-link menus-move menus-move-up' data-dir='up' style='display: none;'>Eén omhoog</button>"+
"<button type='button' class='button-link menus-move menus-move-down' data-dir='down' style='display: inline;' aria-label='Verplaats één omlaag'>Eén omlaag</button>"+
"<button type='button' class='button-link menus-move menus-move-left' data-dir='left' style='display: none;'></button>"+
"<button type='button' class='button-link menus-move menus-move-right' data-dir='right' style='display: none;'></button>"+
"<button type='button' class='button-link menus-move menus-move-top' data-dir='top' style='display: none;'>Naar boven</button>"+
"</fieldset>"+
"<div class='menu-item-actions description-wide submitbox'>"+
"<a class='item-delete submitdelete deletion' id='' href='#'>Verwijderen</a>"+
"</div>"+
"<input type='hidden' value='"+ $(this).val() +"'>"+
"<input type='hidden' value='"+ hidden[2].value +"'>"+
"</div>"+
"</li>";
});
$('#menu-to-edit').append(structure);
checkboxes.prop('checked', false);
};
})
},
Cheers
You're assigning the string on each loop, rather than appending - meaning you only ever get the last one.
One option is to change...
structure = "<li class='menu-item menu-item-depth-0'>"+
To...
structure += "<li class='menu-item menu-item-depth-0'>"+
An alternative option is to append the string on each loop directly...
$(checkboxes).each(function(){
var hidden = $(this).closest('li').find(':hidden');
$('#menu-to-edit').append(
"<li class='menu-item menu-item-depth-0'>"+
"<div class='menu-item-bar'>"+
...
"</div>"+
"</li>");
});
I made a simple example below ( as you didn't share the HTML and a bunch of code you shared is not relevant to the problem itself )
Basically you need to append to the existing HTML. WHat you are doing is replacing it with a new li every time you check a checkbox. So it overrides the previous html.
I also removed the corresponding li when the checkbox is unchecked.
THere might be a more straight forward solution out there but this is the best i came up with for now :)
var chkBox = $(".checkbox")
$(chkBox).on('change', function(){
var index = $(this).index()
var menuItem = `<li class=${index}>${index} list item</li>`
if ($(this).is(':checked') ) {
$('.menu').html($('.menu').html() + menuItem)
} else {
$(`li.${index}`).remove()
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="menu">
</ul>
<div>
<input type="checkbox" class="checkbox"/>
<input type="checkbox" class="checkbox"/>
<input type="checkbox" class="checkbox"/>
<input type="checkbox" class="checkbox"/>
<input type="checkbox" class="checkbox"/>
<input type="checkbox" class="checkbox"/>
</div>

Dynamically appended text field value not geting printed through id in javascript

it is working for first row and after adding second row it is not running please help me to resolve the issue
i Want to use dynamically added text field value in java script
Form
<tr>
<td>
<select required id="itemname-1" name="itemname[]" class="form-control" onchange='showUser(this)'>
<option selected="true" disabled="disabled">Select Item Code</option>
</select>;</td>
<td>
<input type="text" class="form-control col-xs-2" id="quantity-1" placeholder="Quantity" name="quantity[]" style='float:left' onchange="getdetails(this);">
<p id="parameterr-1" style='float:left'></p><input type="hidden" name='parameter[]' id='parameter-1'>
</td>
<td>
<input type="text" class="form-control col-xs-2" id="bp-1" placeholder="Basic Price" name="price[]" onchange="getdetails(this);">
</td>
<td>
<input type="text" class="form-control col-xs-2" id="gst-1" placeholder="GST" name="gst[]" readonly='readonly'>
</td>
<td>
<input type="text" class="form-control col-xs-2" id="tbp-1" placeholder="Total Basic Price" name="tbp[]" readonly='readonly'>
</td>
<td>
<input type="text" class="form-control col-xs-2" id="tgst-1" placeholder="Total GST" name="tgst[]" readonly='readonly'>
</td>
<td>
<input type="text" diasabled class="form-control col-xs-2" id="tot-1" placeholder="Total" name="grand[]" readonly='readonly'>
</td>
<td>
<a href="javascript:void(0);" id="addCF">
<button class="btn-primary btn">Add</button>
</a>
</td>
</tr>
Add Button
<td>
<a href="javascript:void(0);" id="addCF">
<button class="btn-primary btn">Add</button>
</a>
</td>
ADD Form Script
var i = 2;
$(document).ready(function() {
$("#addCF").click(function() {
$("#customFields").append("<tr><td><select required id='itemname-" + i + "' name='itemname[]' class='form-control' onchange='showUser(this);'><option value=''>Select Item Code</option><?php $q='SELECT * FROM items where category="
Raw Material "';$res=mysqli_query($con,$q);while($row=mysqli_fetch_assoc($res)) {echo " < option value = '". $row['
itemid ']."' > " .$row['item_code'] ." < /option>" ;}echo "</select > " ;?></td><td><input type='text' class='form-control col-xs-2' id='quantity-" + i + "' placeholder='Quantity' name='quantity[]' value='0' onchange='getdetails(this);'><p id='parameterr-" + i + "' style='float:left'></p><input type='hidden'name='parameter[]' id='parameter-" + i + "'></td><td><input type='text' class='form-control col-xs-2' id='bp-" + i + " ' placeholder='Basic Price' value='0' name='price[]' onchange='getdetails(this);'></td><td><input type='text' class='form-control col-xs-2' id='gst-" + i + "' placeholder='GST' readonly='readonly' name='gst[]' onblur='tax()'></td><td><input type='text' class='form-control col-xs-2' id='tbp-" + i + "' readonly='readonly' placeholder='Total Basic Price' name='tbp[]'></td><td><input type='text' class='form-control col-xs-2' id='tgst-" + i + "' placeholder='Total GST' name='tgst[]' readonly='readonly'></td><td><input type='text' readonly='readonly' class='form-control col-xs-2' id='tot-" + i + "' placeholder='Total' name='grand[]'></td><td><a href='javascript:void(0);'' id='remCF'><button class='btn-default btn'>Remove</button></a></td></tr>");
i++;
});
$("#customFields").on('click', '#remCF', function() {
$(this).parent().parent().remove();
});
});
I am facing issue while running this function
function getdetails(str) {
var name = str.id;
var res = name.split("-");
var b = res[1];
var qtyid = "quantity-" + b;
var priceid = "bp-" + b;
var tbpid = "tbp-" + b;
var tgstid = "tgst-" + b;
var gstid = "gst-" + b;
var totid = "tot-" + b;
alert(priceid);
var qty = document.getElementById(qtyid).value;
var price = document.getElementById(priceid).value;
var gst = document.getElementById(gstid).value;
if (qty == 0) {
alert("Please Enter Quantity");
} else if (price == 0) {
alert("Please Enter Price");
} else if (price == 0) {
alert("Please Enter Price");
} else if (gst == 0) {
alert("Please Select Item to place purchase Id");
} else {
document.getElementById(tbpid).value = qty * price;
var tbp = document.getElementById(tbpid).value;
var gst = document.getElementById(gstid).value;
document.getElementById(tgstid).value = tbp * (gst / 100);
var tgst = document.getElementById(tgstid).value;
document.getElementById(totid).value = tgst + tbp;
}
}
it is working for first row and after adding second row it is not running please help me to resolve the issue
i Want to use dynamically added text field value in java script
Please check the append string again. Easy solution is to replace :
THIS
$("#customFields").append("<tr><td><select required id='itemname-" + i + "' name='itemname[]' class='form-control' onchange='showUser(this);'><option value=''>Select Item Code</option><?php $q='SELECT * FROM items where category="
Raw Material "';$res=mysqli_query($con,$q);while($row=mysqli_fetch_assoc($res)) {echo " < option value = '". $row['
itemid ']."' > " .$row['item_code'] ." < /option>" ;}echo "</select > " ;?></td><td><input type='text' class='form-control col-xs-2' id='quantity-" + i + "' placeholder='Quantity' name='quantity[]' value='0' onchange='getdetails(this);'><p id='parameterr-" + i + "' style='float:left'></p><input type='hidden'name='parameter[]' id='parameter-" + i + "'></td><td><input type='text' class='form-control col-xs-2' id='bp-" + i + " ' placeholder='Basic Price' value='0' name='price[]' onchange='getdetails(this);'></td><td><input type='text' class='form-control col-xs-2' id='gst-" + i + "' placeholder='GST' readonly='readonly' name='gst[]' onblur='tax()'></td><td><input type='text' class='form-control col-xs-2' id='tbp-" + i + "' readonly='readonly' placeholder='Total Basic Price' name='tbp[]'></td><td><input type='text' class='form-control col-xs-2' id='tgst-" + i + "' placeholder='Total GST' name='tgst[]' readonly='readonly'></td><td><input type='text' readonly='readonly' class='form-control col-xs-2' id='tot-" + i + "' placeholder='Total' name='grand[]'></td><td><a href='javascript:void(0);'' id='remCF'><button class='btn-default btn'>Remove</button></a></td></tr>");
WITH
$("#customFields").append(`<tr><td><select required id='itemname-" + i + "' name='itemname[]' class='form-control' onchange='showUser(this);'><option value=''>Select Item Code</option><?php $q='SELECT * FROM items where category="
Raw Material "';$res=mysqli_query($con,$q);while($row=mysqli_fetch_assoc($res)) {echo " < option value = '". $row['
itemid ']."' > " .$row['item_code'] ." < /option>" ;}echo "</select > " ;?></td><td><input type='text' class='form-control col-xs-2' id='quantity-" + i + "' placeholder='Quantity' name='quantity[]' value='0' onchange='getdetails(this);'><p id='parameterr-" + i + "' style='float:left'></p><input type='hidden'name='parameter[]' id='parameter-" + i + "'></td><td><input type='text' class='form-control col-xs-2' id='bp-" + i + " ' placeholder='Basic Price' value='0' name='price[]' onchange='getdetails(this);'></td><td><input type='text' class='form-control col-xs-2' id='gst-" + i + "' placeholder='GST' readonly='readonly' name='gst[]' onblur='tax()'></td><td><input type='text' class='form-control col-xs-2' id='tbp-" + i + "' readonly='readonly' placeholder='Total Basic Price' name='tbp[]'></td><td><input type='text' class='form-control col-xs-2' id='tgst-" + i + "' placeholder='Total GST' name='tgst[]' readonly='readonly'></td><td><input type='text' readonly='readonly' class='form-control col-xs-2' id='tot-" + i + "' placeholder='Total' name='grand[]'></td><td><a href='javascript:void(0);'' id='remCF'><button class='btn-default btn'>Remove</button></a></td></tr>`);

Jquery works in JSFiddle but not works in computer

This is the answer I get from jsfiddle. It's working on the fiddle part, but it's not working when I move it to my computer. I replaced the code in my program and also included all of the external resource library. However, it's still not working at all.
var x = 1;
function appendRow() {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + x);
// I ASSIGNED A CLASS CALLED INPUT TO THE ELEMENT YOU WANT TO SELECT
newTextBoxDiv.after().html("<div class='form-group'><label class='control-label col-sm-3' style='text-align:right;'>Date:</label><div class='col-sm-3'><div class='input-group date' ><span class='input-group-addon'><i class='fa fa-calendar'></i></span><input type='Date' class='form-control' name='Dates'> <select class='form-control input' id='slct" + x + "' name='Branch''><option disabled='' selected=''>Please Select Leave Day</option> <option value='1' >1</option><option value='0.5' >0.5</option></select></div></span></div><div id='container" + x + "'></div></div>");
newTextBoxDiv.appendTo("#div");
x++;
}
function changeIt(rowIndex) {
//i++; DO NOT INCREMENT I!!! IT WILL CREATE THE REFERRAL ERROR YOU HAD. BECAUSE THE FUNCTION WOULD BE REFERRING TO A NON-EXISTING INPUT ELEMENT. I REPLACED IT WITH ROWINDEX, WHICH IS INITIATED WHILE CALLING THE FUNCTION
var select = document.getElementById("slct" + rowIndex);
var divv = document.getElementById("container" + rowIndex);
var value = select.value;
if (value == 0.5) {
toAppend = "<label class='control-label col-sm-1'>Time:</label><div class='col-sm-2'><div class='input-group date' id = 'date'> <span class='input-group-addon'><i class='fa fa-clock-o'></i></span><input type='time' class='form-control' ></div></div><div class='col-sm-2'><div class='input-group date' id = 'dates'> <span class='input-group-addon'><i class='fa fa-clock-o'></i></span><input type='time' class='form-control' ></div></div>";
divv.innerHTML = toAppend;
return;
}
if (value == 1) {
toAppend = "";
divv.innerHTML = toAppend;
return;
}
}
$("#button").click(function() {
appendRow();
});
$("#div").on("change", ".input", function() {
//EXTRACT THE NUMBER FROM THE CLICKED ITEM'S ID
let rowIndex = $(this).attr("id").replace(/.[^0-9]/g, "");
changeIt(rowIndex);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div">
<button value="Add Row" id="button">Add row</button>
</div>
make sure your script is below the html for your button
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div">
<button value="Add Row" id="button">Add row</button>
</div>
<!-- your js goes here -->
<script>
var x = 1;
function appendRow() {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + x);
// I ASSIGNED A CLASS CALLED INPUT TO THE ELEMENT YOU WANT TO SELECT
newTextBoxDiv.after().html("<div class='form-group'><label class='control-label col-sm-3' style='text-align:right;'>Date:</label><div class='col-sm-3'><div class='input-group date' ><span class='input-group-addon'><i class='fa fa-calendar'></i></span><input type='Date' class='form-control' name='Dates'> <select class='form-control input' id='slct" + x + "' name='Branch''><option disabled='' selected=''>Please Select Leave Day</option> <option value='1' >1</option><option value='0.5' >0.5</option></select></div></span></div><div id='container" + x + "'></div></div>");
newTextBoxDiv.appendTo("#div");
x++;
}
function changeIt(rowIndex) {
//i++; DO NOT INCREMENT I!!! IT WILL CREATE THE REFERRAL ERROR YOU HAD. BECAUSE THE FUNCTION WOULD BE REFERRING TO A NON-EXISTING INPUT ELEMENT. I REPLACED IT WITH ROWINDEX, WHICH IS INITIATED WHILE CALLING THE FUNCTION
var select = document.getElementById("slct" + rowIndex);
var divv = document.getElementById("container" + rowIndex);
var value = select.value;
if (value == 0.5) {
toAppend = "<label class='control-label col-sm-1'>Time:</label><div class='col-sm-2'><div class='input-group date' id = 'date'> <span class='input-group-addon'><i class='fa fa-clock-o'></i></span><input type='time' class='form-control' ></div></div><div class='col-sm-2'><div class='input-group date' id = 'dates'> <span class='input-group-addon'><i class='fa fa-clock-o'></i></span><input type='time' class='form-control' ></div></div>";
divv.innerHTML = toAppend;
return;
}
if (value == 1) {
toAppend = "";
divv.innerHTML = toAppend;
return;
}
}
$("#button").click(function() {
console.log('test');
appendRow();
});
$("#div").on("change", ".input", function() {
//EXTRACT THE NUMBER FROM THE CLICKED ITEM'S ID
let rowIndex = $(this).attr("id").replace(/.[^0-9]/g, "");
changeIt(rowIndex);
});</script>
Here you go with the solution
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var x = 1;
function appendRow() {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + x);
// I ASSIGNED A CLASS CALLED INPUT TO THE ELEMENT YOU WANT TO SELECT
newTextBoxDiv.after().html("<div class='form-group'><label class='control-label col-sm-3' style='text-align:right;'>Date:</label><div class='col-sm-3'><div class='input-group date' ><span class='input-group-addon'><i class='fa fa-calendar'></i></span><input type='Date' class='form-control' name='Dates'> <select class='form-control input' id='slct" + x + "' name='Branch''><option disabled='' selected=''>Please Select Leave Day</option> <option value='1' >1</option><option value='0.5' >0.5</option></select></div></span></div><div id='container" + x + "'></div></div>");
newTextBoxDiv.appendTo("#div");
x++;
}
function changeIt(rowIndex) {
//i++; DO NOT INCREMENT I!!! IT WILL CREATE THE REFERRAL ERROR YOU HAD. BECAUSE THE FUNCTION WOULD BE REFERRING TO A NON-EXISTING INPUT ELEMENT. I REPLACED IT WITH ROWINDEX, WHICH IS INITIATED WHILE CALLING THE FUNCTION
var select = document.getElementById("slct" + rowIndex);
var divv = document.getElementById("container" + rowIndex);
var value = select.value;
if (value == 0.5) {
toAppend = "<label class='control-label col-sm-1'>Time:</label><div class='col-sm-2'><div class='input-group date' id = 'date'> <span class='input-group-addon'><i class='fa fa-clock-o'></i></span><input type='time' class='form-control' ></div></div><div class='col-sm-2'><div class='input-group date' id = 'dates'> <span class='input-group-addon'><i class='fa fa-clock-o'></i></span><input type='time' class='form-control' ></div></div>";
divv.innerHTML = toAppend;
return;
}
if (value == 1) {
toAppend = "";
divv.innerHTML = toAppend;
return;
}
}
$("#button").click(function() {
console.log('test');
appendRow();
});
$("#div").on("change", ".input", function() {
//EXTRACT THE NUMBER FROM THE CLICKED ITEM'S ID
let rowIndex = $(this).attr("id").replace(/.[^0-9]/g, "");
changeIt(rowIndex);
});
});</script>
</head>
<body>
<div id="div">
<button value="Add Row" id="button">Add row</button>
</div>
<!-- your js goes here -->
</body>
</html>
I think you forgot to add $(document).ready(function(){});
I tested in my local & it's working.

Function doesn't work in Javascript (increase/decrease button)

I want to make increase/decrease button work when I click the button. I put the section in JavaScript(using as part of a function to insert into HTML file), but it doesn't work. The code in JavaScript is as below:
string ="<img class='minubtn' src='images/delete.png' onclick='javascript:
document.getElementById('countNo1').value--;' />"+
"<input type='text' id='countNo1' class='txtCount' value='0' placeholder='0'/>"+
"<img class='addbtn' src='images/add.png' onclick='javascript:
document.getElementById('countNo1').value++;'/>"
I find the reason why it's not working. In nested string, I need to use \' \' instead of '' to quote the id. So the code should like this:
string ="<img class='minubtn' src='images/delete.png' onclick='javascript:
document.getElementById(\'countNo1\').value--;' />"+
"<input type='text' id='countNo1' class='txtCount' value='0' placeholder='0'/>"+
"<img class='addbtn' src='images/add.png' onclick='javascript:
document.getElementById(\'countNo1\').value++;'/>"
Here:
This might help you
HTML:
<input type="text" name="count" value="0" id="count">
<input type="button" value="+1" onclick="operate('add')">
<input type="button" value="-1" onclick="operate('dec')">
Script:
<script>
function operate(val){
if(val == "add"){
var val = document.getElementById('count').value;
val++;
document.getElementById('count').value = val;
} else{
var val = document.getElementById('count').value;
val--;
document.getElementById('count').value = val;
}
}
</script>

How to append check box in jquery

How I add checkbox after span in below code.
var aaa = $('<a/>')
.html("<span>" "</span >" + " <span>""</span> ")
.attr('data-transition', 'slide')
.appendTo(li);
Your .html() has several issues with concatenation:
.html("<span>" "</span >" + " <span>""</span> ")
//------^^^^--------------------^^--------useless quotes are here.
this way:
.html("<span></span ><input type='checkbox' value='' />" + " <span>""</span> ")
this way:
.html("<span></span >" + " <span></span><input type='checkbox' value='' />")
or after both:
.html("<span></span> <input type='checkbox' value='' />" + " <span></span><input type='checkbox' value='' />")
just add the html tag for checkbox inside <span>
try this
.html("<span> <input type='checkbox' value='value' />test<input type='checkbox' value='value1' />test1</span >") ;
You can also make use of the html option.
var $a = $("<a/>", {
"data-transition": "slide",
"html": $("<input>", {
"type": "checkbox"
})
})
.appendTo(li);
It will render this HTML:
<a data-transition="slide"><input type="checkbox"></a>

Categories