Cascading Dropdown list in html not working when appended - javascript

I have a cascading dropdown lists (or dependant dropdown lists) using javascript which works fine. I would like to be able to append the html with this cascading dropdown list. The issue i'm now having is, when I append the html the dropdown list in the appended html doesn't work. Not sure how to rectify this, any help would be much appreciated. Thank you.
<html>
<head>
<!--CASCADING JS-->
<script>
var subjectObject = {
"Mattress": {
"75x30x3":["20", "22", "35"],
"75x30x4":["20", "22", "35"],
"75x30x6":["20", "22", "35"],
"75x36x3":["20", "22", "35"],
},
"Orthopaedic": {
"75x54x6":["N/A"],
"75x54x8":["N/A"],
"75x54x10":["N/A"],
},
"Block": {
"108":["13", "16", "18", "20", "22", "35"],
"88":["13", "16", "18", "20", "22", "35"],
}
window.onload = function() {
var subjectSel = document.getElementById("subject");
var topicSel = document.getElementById("topic");
var chapterSel = document.getElementById("chapter");
for (var x in subjectObject) {
subjectSel.options[subjectSel.options.length] = new Option(x, x);
}
subjectSel.onchange = function() {   
//empty Chapters- and Topics- dropdowns
chapterSel.length = 1; topicSel.length = 1;
//display correct values
for (var y in subjectObject[this.value]) {
topicSel.options[topicSel.options.length] = new Option(y, y);
}
}
topicSel.onchange = function() { //empty Chapters dropdown chapterSel.length = 1;
//display correct values
var z = subjectObject[subjectSel.value][this.value];
for (var i = 0; i < z.length; i++) {
chapterSel.options[chapterSel.options.length] = new Option(z[i], z[i]);
}
}
}
</script>
<!---END OF CASCADING JS-->
<!------ START OF APPENDED JS--------->
<script> //START OF APPENDED HTML (via JS)
function myFunction() {
var html =
'<div class="container">' +
'<div class="grid-item">' +
'<label for="itempurchased">' +
'<span style="color:darkred; font-size:14px; padding-top: -14px">Item:
</span>' +
'</label>' +
'</div>' +
'<div class="grid-item">' +
'<select name="subject" id="subject">' +
'<option value="" selected="selected" style="font-style: italic">Select Item</option>' +
'</select>' +
'</div>' +
'<div class="grid-item">' +
'<label for="size">' +
'<span style="color:darkred; font-size:14px">Size:</span>' +
'</label>' +
'</div>' +
'<div class="grid-item">' +
'<select name="topic" id="topic">' +
'<option value="" selected="selected" style="font-style: italic">Select Size</option>' +
'</select>' +
'</div>' +
'<div class="grid-item">' +
'<label for="density">' +
'<span style="color:darkred; font-size:14px">Density:</span>' +
'</label>' +
'</div>' +
'<div class="grid-item">' +
'<select name="chapter" id="chapter">' +
'<option value="" selected="selected" style="font-style: italic">Select Density</option>' +
'</select>' +
'</div>' +
'<div class="grid-item">' +
'<label for="qty">' +
'<span style="color:darkred; font-size:14px">Qty:</span>' +
'</label>' +
'</div>' +
'<div class="grid-item">' +
'<input type="text" name="qty" id="qty">' +
'</div>' +
'</div>' +
'<hr>';
$('div.additem').append(html).trigger('create');
}
</script>
<!------ END OF APPENDED HTML--------->
</head>
<body>
<html>
HTML
<form>
<div class="sales">
<div class="customer">
<label for="customer"> Customer Name:</label> <input type="text" name="customername" id="customername">
</div>
<hr>
<div>
<div class="container">
<div class="grid-item">
<label for="itempurchased">
<span style="color:darkred; font-size:14px; padding-top: -14px">Item:
</span>
</label>
</div>
<div class="grid-item">
<select name="subject" id="subject">
<option value="" selected="selected" style="font-style: italic">Select Item</option>
</select>
</div>
<div class="grid-item">
<label for="size">
<span style="color:darkred; font-size:14px">Size:</span>
</label>
</div>
<div class="grid-item">
<select name="topic" id="topic">
<option value="" selected="selected" style="font-style: italic">Select Size</option>
</select>
</div>
<div class="grid-item">
<label for="density">
<span style="color:darkred; font-size:14px">Density:</span>
</label>
</div>
<div class="grid-item">
<select name="chapter" id="chapter">
<option value="" selected="selected" style="font-style: italic">Select Density</option>
</select>
</div>
<div class="grid-item">
<label for="qty">
<span style="color:darkred; font-size: 14px">Qty:</span>
</label>
</div>
<div class="grid-item">
<input type="text" name="qty" id="qty">
</div>
</div>
<hr>
<!--div for add item-->
<div class="additem"></div>
</div>
<!--------------ACTION BUTTONS------------->
<div class="payment">
<input type="submit" value="GO TO PAYMENT" name="btnSubmit" data-theme="d" id="btnSubmit" data-ajax="false">
</div>
<div class="add_item">
<button onclick="myFunction()" data-theme="d" data-corners="5px" type="button">ADD ITEM</button>
</div>
</div>
</form>
</body>
</html>

You have a few syntax errors in your JS code:
Missing closing curly brace, before window.onload = function..., to match the opening one of var subjectObject = {
On line 7 of your second script, you have a new line after Item:. Your code could use some formatting love.
https://jsfiddle.net/02ejx9wq/
var subjectObject = {
"Mattress": {
"75x30x3": ["20", "22", "35"],
"75x30x4": ["20", "22", "35"],
"75x30x6": ["20", "22", "35"],
"75x36x3": ["20", "22", "35"],
},
"Orthopaedic": {
"75x54x6": ["N/A"],
"75x54x8": ["N/A"],
"75x54x10": ["N/A"],
},
"Block": {
"108": ["13", "16", "18", "20", "22", "35"],
"88": ["13", "16", "18", "20", "22", "35"],
}
}
window.onload = function() {
var subjectSel = document.getElementById("subject");
var topicSel = document.getElementById("topic");
var chapterSel = document.getElementById("chapter");
for (var x in subjectObject) {
subjectSel.options[subjectSel.options.length] = new Option(x, x);
}
subjectSel.onchange = function() {
//empty Chapters- and Topics- dropdowns
chapterSel.length = 1;
topicSel.length = 1;
//display correct values
for (var y in subjectObject[this.value]) {
topicSel.options[topicSel.options.length] = new Option(y, y);
}
}
topicSel.onchange = function() { //empty Chapters dropdown chapterSel.length = 1;
//display correct values
var z = subjectObject[subjectSel.value][this.value];
for (var i = 0; i < z.length; i++) {
chapterSel.options[chapterSel.options.length] = new Option(z[i], z[i]);
}
}
}
function myFunction() {
var html =
'<div class="container">' +
'<div class="grid-item">' +
'<label for="itempurchased">' +
'<span style="color:darkred; font-size:14px; padding-top: -14px">Item: </span>' +
'</label>' +
'</div>' +
'<div class="grid-item">' +
'<select name="subject" id="subject">' +
'<option value="" selected="selected" style="font-style: italic">Select Item</option>' +
'</select>' +
'</div>' +
'<div class="grid-item">' +
'<label for="size">' +
'<span style="color:darkred; font-size:14px">Size:</span>' +
'</label>' +
'</div>' +
'<div class="grid-item">' +
'<select name="topic" id="topic">' +
'<option value="" selected="selected" style="font-style: italic">Select Size</option>' +
'</select>' +
'</div>' +
'<div class="grid-item">' +
'<label for="density">' +
'<span style="color:darkred; font-size:14px">Density:</span>' +
'</label>' +
'</div>' +
'<div class="grid-item">' +
'<select name="chapter" id="chapter">' +
'<option value="" selected="selected" style="font-style: italic">Select Density</option>' +
'</select>' +
'</div>' +
'<div class="grid-item">' +
'<label for="qty">' +
'<span style="color:darkred; font-size:14px">Qty:</span>' +
'</label>' +
'</div>' +
'<div class="grid-item">' +
'<input type="text" name="qty" id="qty">' +
'</div>' +
'</div>' +
'<hr>';
$('div.additem').append(html).trigger('create');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
HTML
<form>
<div class="sales">
<div class="customer">
<label for="customer"> Customer Name:</label> <input type="text" name="customername" id="customername">
</div>
<hr>
<div>
<div class="container">
<div class="grid-item">
<label for="itempurchased">
<span style="color:darkred; font-size:14px; padding-top: -14px">Item:
</span>
</label>
</div>
<div class="grid-item">
<select name="subject" id="subject">
<option value="" selected="selected" style="font-style: italic">Select Item</option>
</select>
</div>
<div class="grid-item">
<label for="size">
<span style="color:darkred; font-size:14px">Size:</span>
</label>
</div>
<div class="grid-item">
<select name="topic" id="topic">
<option value="" selected="selected" style="font-style: italic">Select Size</option>
</select>
</div>
<div class="grid-item">
<label for="density">
<span style="color:darkred; font-size:14px">Density:</span>
</label>
</div>
<div class="grid-item">
<select name="chapter" id="chapter">
<option value="" selected="selected" style="font-style: italic">Select Density</option>
</select>
</div>
<div class="grid-item">
<label for="qty">
<span style="color:darkred; font-size: 14px">Qty:</span>
</label>
</div>
<div class="grid-item">
<input type="text" name="qty" id="qty">
</div>
</div>
<hr>
<!--div for add item-->
<div class="additem"></div>
</div>
<!--------------ACTION BUTTONS------------->
<div class="payment">
<input type="submit" value="GO TO PAYMENT" name="btnSubmit" data-theme="d" id="btnSubmit" data-ajax="false">
</div>
<div class="add_item">
<button onclick="myFunction()" data-theme="d" data-corners="5px" type="button">ADD ITEM</button>
</div>
</div>
</form>

Related

Change data format in CRUD output to dd/mm/yyy [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 4 months ago.
i know it's a question asked many times here, but i tried all the solutions and no one is working.
I want to change the output in my CRUD from the input form to dd/mm/yyyy and not in yyyy-mm-dd.
Here's my code:
var nextId = 1;
var activeId = 0;
function productDisplay(ctl) {
var row = $(ctl).parents("tr");
var cols = row.children("td");
activeId = $($(cols[0]).children("button")[0]).data("id");
$("#productname").val($(cols[1]).text());
$("#introdate").val($(cols[2]).text());
$("#finishdate").val($(cols[3]).text());
$("#url").val($(cols[4]).text());
$("#phone").val($(cols[5]).text());
$("#note").val($(cols[6]).text());
$("#client").val($(cols[7]).text());
$("#updateButton").text("Aggiorna");
}
function productUpdate() {
if ($("#updateButton").text() == "Add") {
productUpdateInTable(activeId);
}
else {
productAddToTable();
}
formClear();
$("#productname").focus();
}
function productAddToTable() {
if ($("#productTable tbody").length == 0) {
$("#productTable").append("<tbody></tbody>");
}
$("#productTable tbody").append(
productBuildTableRow(nextId));
nextId += 1;
}
function productUpdateInTable(id) {
var row = $("#productTable button[data-id='" + id + "']")
.parents("tr")[0];
$(row).after(productBuildTableRow(id));
$(row).remove();
formClear();
$("#updateButton").text("Add");
}
function productBuildTableRow(id) {
var ret =
"<tr>" +
"<td>" +
"<button type='button' " +
"onclick='productDisplay(this);' " +
"class='btn btn-default' " +
"data-id='" + id + "'>" +
"<span class='glyphicon glyphicon-pencil' />" +
"</button>" +
"</td>" +
"<td>" + $("#productname").val() + "</td>" +
"<td>" + $("#introdate").val() + "</td>" +
"<td>" + $("#finishdate").val() + "</td>" +
"<td>" + $("#url").val() + "</td>" +
"<td>" + $("#phone").val() + "</td>" +
"<td>" + $("#note").val() + "</td>" +
"<td>" + $("#client").val() + "</td>" +
"<td>" +
"<button type='button' " +
"onclick='productDelete(this);' " +
"class='btn btn-default' " +
"data-id='" + id + "'>" +
"<span class='glyphicon glyphicon-minus' />" +
"</button>" +
"</td>" +
"</tr>"
return ret;
}
function productDelete(ctl) {
var result = confirm("Want to delete record?");
if (result) {
var result2 = confirm("Really?");
}
if (result2) {
$(ctl).parents("tr").remove();
}
}
function formClear() {
$("#productname").val("");
$("#introdate").val("");
$("#finishdate").val("");
$("#url").val("");
$("#phone").val("");
$("#note").val("");
$("#client").val("");
}
function doSearch(text, color = "yellow") {
if (color != "transparent") {
doSearch(document.getElementById('hid_search').value, "transparent");
document.getElementById('hid_search').value = text;
}
if (window.find && window.getSelection) {
document.designMode = "on";
var sel = window.getSelection();
sel.collapse(document.body, 0);
while (window.find(text)) {
document.execCommand("HiliteColor", false, color);
sel.collapseToEnd();
}
document.designMode = "off";
} else if (document.body.createTextRange) {
var textRange = document.body.createTextRange();
while (textRange.findText(text)) {
textRange.execCommand("BackColor", false, color);
textRange.collapse(false);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-6">
<h2><b>Availability</h2></b>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<table id="productTable" class="table table-bordered table-condensed table-striped">
<thead>
<tr>
<th class="col-sm-0">Modify</th>
<th class="col-sm-2">Name</th>
<th class="col-sm-1">From</th>
<th class="col-sm-1">To</th>
<th class="col-sm-2">Area</th>
<th class="col-sm-2">Phone</th>
<th class="col-sm-3">Note</th>
<th class="col-sm-2">Client</th>
<th class="col-sm-0">Delete</th>
</tr>
</thead>
</table>
</div>
</div>
<div class="row">
<div class="col-sm-5">
<div class="panel panel-primary">
<div class="panel-heading">
Add Availability
</div>
<div class="panel-body">
<div class="form-group">
<label for="productname">
Name
</label>
<input type="text" class="form-control" value="" id="productname" />
</div>
<div class="form-group">
<label for="introdate">
From
</label>
<input type="date" class="form-control" value="gg/mm/aaaa" id="introdate">
</div>
<div class="form-group">
<label for="introdate">
To
</label>
<input type="date" class="form-control" value="gg/mm/aaaa" id="finishdate" />
</div>
<div class="form-group">
<label for="area">
Area
</label>
<input type="search" class="form-control" value="" id="url" />
</div>
<div class="form-group">
<label for="phone">
Phone
</label>
<input type="" class="form-control" value="" id="phone" />
</div>
<div class="form-group">
<label for="note">
Note
</label>
<input type="" class="form-control" value="" id="note" />
</div>
<div class="form-group">
<label for="client">
Client
</label>
<select id="client" class="form-control">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</div>
<div class="panel-footer">
<div class="row">
<div class="col-xs-12">
<button type="button" id="updateButton" class="btn btn-primary" onclick="productUpdate();">
Add
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
When I insert a new record from form field date, the output in my CRUD is like YYYY-MM-DD.
This should help you. Pass a valid date in any format and the function will return a dd/mm/yyyy date format
// Helper function to format date from $(input).val()
function formatDate(date) {
if (date == '') {
return '';
}
let d = new Date(date),
ye = new Intl.DateTimeFormat('en', {
year: 'numeric'
}).format(d),
mo = new Intl.DateTimeFormat('en', {
month: '2-digit'
}).format(d),
da = new Intl.DateTimeFormat('en', {
day: '2-digit'
}).format(d);
return (`${da}-${mo}-${ye}`);
}
// ----
var nextId = 1;
var activeId = 0;
function productDisplay(ctl) {
var row = $(ctl).parents("tr");
var cols = row.children("td");
activeId = $($(cols[0]).children("button")[0]).data("id");
$("#productname").val($(cols[1]).text());
$("#introdate").val($(cols[2]).text());
$("#finishdate").val($(cols[3]).text());
$("#url").val($(cols[4]).text());
$("#phone").val($(cols[5]).text());
$("#note").val($(cols[6]).text());
$("#client").val($(cols[7]).text());
$("#updateButton").text("Aggiorna");
}
function productUpdate() {
if ($("#updateButton").text() == "Add") {
productUpdateInTable(activeId);
}
else {
productAddToTable();
}
formClear();
$("#productname").focus();
}
function productAddToTable() {
if ($("#productTable tbody").length == 0) {
$("#productTable").append("<tbody></tbody>");
}
$("#productTable tbody").append(
productBuildTableRow(nextId));
nextId += 1;
}
function productUpdateInTable(id) {
var row = $("#productTable button[data-id='" + id + "']")
.parents("tr")[0];
$(row).after(productBuildTableRow(id));
$(row).remove();
formClear();
$("#updateButton").text("Add");
}
function productBuildTableRow(id) {
var ret =
"<tr>" +
"<td>" +
"<button type='button' " +
"onclick='productDisplay(this);' " +
"class='btn btn-default' " +
"data-id='" + id + "'>" +
"<span class='glyphicon glyphicon-pencil' />" +
"</button>" +
"</td>" +
"<td>" + $("#productname").val() + "</td>" +
"<td>" + formatDate($("#introdate").val()) + "</td>" + // call helper function
"<td>" + formatDate($("#finishdate").val()) + "</td>" + // call helper function
"<td>" + $("#url").val() + "</td>" +
"<td>" + $("#phone").val() + "</td>" +
"<td>" + $("#note").val() + "</td>" +
"<td>" + $("#client").val() + "</td>" +
"<td>" +
"<button type='button' " +
"onclick='productDelete(this);' " +
"class='btn btn-default' " +
"data-id='" + id + "'>" +
"<span class='glyphicon glyphicon-minus' />" +
"</button>" +
"</td>" +
"</tr>"
return ret;
}
function productDelete(ctl) {
var result = confirm("Want to delete record?");
if (result) {
var result2 = confirm("Really?");
}
if (result2) {
$(ctl).parents("tr").remove();
}
}
function formClear() {
$("#productname").val("");
$("#introdate").val("");
$("#finishdate").val("");
$("#url").val("");
$("#phone").val("");
$("#note").val("");
$("#client").val("");
}
function doSearch(text, color = "yellow") {
if (color != "transparent") {
doSearch(document.getElementById('hid_search').value, "transparent");
document.getElementById('hid_search').value = text;
}
if (window.find && window.getSelection) {
document.designMode = "on";
var sel = window.getSelection();
sel.collapse(document.body, 0);
while (window.find(text)) {
document.execCommand("HiliteColor", false, color);
sel.collapseToEnd();
}
document.designMode = "off";
} else if (document.body.createTextRange) {
var textRange = document.body.createTextRange();
while (textRange.findText(text)) {
textRange.execCommand("BackColor", false, color);
textRange.collapse(false);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-6">
<h2><b>Availability</h2></b>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<table id="productTable" class="table table-bordered table-condensed table-striped">
<thead>
<tr>
<th class="col-sm-0">Modify</th>
<th class="col-sm-2">Name</th>
<th class="col-sm-1">From</th>
<th class="col-sm-1">To</th>
<th class="col-sm-2">Area</th>
<th class="col-sm-2">Phone</th>
<th class="col-sm-3">Note</th>
<th class="col-sm-2">Client</th>
<th class="col-sm-0">Delete</th>
</tr>
</thead>
</table>
</div>
</div>
<div class="row">
<div class="col-sm-5">
<div class="panel panel-primary">
<div class="panel-heading">
Add Availability
</div>
<div class="panel-body">
<div class="form-group">
<label for="productname">
Name
</label>
<input type="text" class="form-control" value="" id="productname" />
</div>
<div class="form-group">
<label for="introdate">
From
</label>
<input type="date" class="form-control" value="gg/mm/aaaa" id="introdate">
</div>
<div class="form-group">
<label for="introdate">
To
</label>
<input type="date" class="form-control" value="gg/mm/aaaa" id="finishdate" />
</div>
<div class="form-group">
<label for="area">
Area
</label>
<input type="search" class="form-control" value="" id="url" />
</div>
<div class="form-group">
<label for="phone">
Phone
</label>
<input type="" class="form-control" value="" id="phone" />
</div>
<div class="form-group">
<label for="note">
Note
</label>
<input type="" class="form-control" value="" id="note" />
</div>
<div class="form-group">
<label for="client">
Client
</label>
<select id="client" class="form-control">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</div>
<div class="panel-footer">
<div class="row">
<div class="col-xs-12">
<button type="button" id="updateButton" class="btn btn-primary" onclick="productUpdate();">
Add
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

multiple dynamic input onchange and onblur function javascript

I have multiple input that when you select the option, the stock and the price would come out on other input to be used for another function.
i've tried to add unique id's for the inputs added but i just cant seem to figure out how to apply the function to the added inputs.
here is the Html:
<div id="container1">
<div class="form-group row">
<div class="col-lg-3">
<select class="form-control border-teal" id="produk_nama1" name="produk_nama[]">
<option value="">Pilih Produk</option>
#foreach ($stoks as $stok)
<option data-stok="{{$stok->stok}}" data-price="{{$stok->harga}}" value="{{$stok->produk->produk}}">{{$stok->produk->produk}}</option>
#endforeach
</select>
<div class="d-block form-text">
<span id="stok1" class="badge bg-orange"></span>
</div>
</div>
<div class="col-lg-3">
<input type="text" id="harga1" name="harga[]" class="form-control border-teal border-1" placeholder="Harga Produk" readonly>
</div>
<div class="col-lg-3">
<input type="number" id="jumlah1" name="jumlah[]" min="1" class="form-control border-teal border-1" placeholder="Masukkan Jumlah">
</div>
<div class="col-lg-3">
<input type="text" id="subtotal1" name="subtotal" class="form-control border-teal border-1" placeholder="Subtotal" readonly>
</div>
</div>
</div>
here is the javascript:
$(document).ready(function() {
var add_button = $("#add_button");
var inputs = document.getElementsByTagName('input');
var select = document.getElementById("produk_nama");
var i = 1;
$(add_button).click(function(e) {
e.preventDefault();
i++;
$("#container1")
var html = '<div class="form-group row">';
// select buah
html += '<div class="col-lg-3">';
html += '<select class="form-control border-teal" id="produk_nama'+i+'" name="produk_nama[]">';
html += '<option value="">Pilih Produk</option>';
html += '#foreach ($stoks as $stok)';
html += '<option data-stok="{{$stok->stok}}" data-price="{{$stok->harga}}" value="{{$stok->produk->produk}}">{{$stok->produk->produk}}</option>';
html += '#endforeach';
html += '</select>';
html += '<div class="d-block form-text">';
html += '<span id="stok'+i+'" class="badge bg-orange"></span>';
html += '</div></div>';
html += '<div class="col-lg-3">';
html += '<input type="text" id="harga'+i+'" name="harga[]" class="form-control border-teal border-1" placeholder="Harga Produk" readonly>';
html += '</div>';
html += '<div class="col-lg-3">';
html += '<input type="number" id="jumlah'+i+'" name="jumlah[]" min="1" class="form-control border-teal border-1" placeholder="Masukkan Jumlah">';
html += '</div>';
html += '<div class="col-lg-3">';
html += '<input type="text" id="subtotal'+i+'" name="subtotal" class="form-control border-teal border-1" placeholder="Subtotal" readonly>';
html += '</div>';
html += '</div>';
$(this).before(html);
// clone entire div
// $("#container1")
// .append(
// $("#container1")
// .children(inputs)
// .first()
// .clone()
// )
});
// main input function
$('#produk_nama'+i).on('change', function(){
alert(i);
var hargaproduk = $('#produk_nama'+i+' option:selected').data('price');
var stok = $('#produk_nama'+i+' option:selected').data('stok');
$('#stok'+i).text('Stok '+stok);
$('#harga'+i).val(hargaproduk);
});
document.getElementById('jumlah'+i).addEventListener("blur", function(){
var jumlah = $('#jumlah'+i).val();
var harga = $('#harga'+i).val();
var subtotal = jumlah * harga;
$('#subtotal'+i).val(subtotal);
})
});
any help and explanation would be much appreciated, thank you
As your first select-box i.e :produk_nama is same for all divs you can use clone() method to get clone of that select instead of writing laravel code inside jquery code.
Then , you can use $(document).on("change", "select[name*=produk_nama]".. to capture all change event on select-box . Inside this you can use .closest() and .find() method to get required values from input you needed and add the value to required inputs.Same you can do for jumlah input .
Demo Code :
$(document).ready(function() {
var add_button = $("#add_button");
var i = 1;
$(add_button).click(function(e) {
e.preventDefault();
i++;
$("#container1")
//get first div > selct clone it
var slects = $('.outer:first').find("select").clone();
var html = '<div class="form-group row outer">';
html += '<div class="col-lg-3">';
html += '<select class="form-control border-teal" id="produk_nama' + i + '" name="produk_nama[]">';
html += $(slects).html(); //add that
html += '</select>';
html += '<div class="d-block form-text">';
html += '<span id="stok' + i + '" class="badge bg-orange"></span>';
html += '</div></div>';
html += '<div class="col-lg-3">';
html += '<input type="text" id="harga' + i + '" name="harga[]" class="form-control border-teal border-1" placeholder="Harga Produk" readonly>';
html += '</div>';
html += '<div class="col-lg-3">';
html += '<input type="number" id="jumlah' + i + '" name="jumlah[]" min="1" class="form-control border-teal border-1" placeholder="Masukkan Jumlah">';
html += '</div>';
html += '<div class="col-lg-3">';
html += '<input type="text" id="subtotal' + i + '" name="subtotal" class="form-control border-teal border-1" placeholder="Subtotal" readonly>';
html += '</div>';
html += '</div>';
$(this).before(html);
});
//on change of selct
$(document).on("change", "select[name*=produk_nama]", function() {
//get attrs values
var hargaproduk = $(this).find("option:selected").attr('data-price');
var stok = $(this).find("option:selected").attr('data-stok');
//add the values to required elemnt
$(this).closest(".outer").find(".d-block span").text('Stok ' + stok)
$(this).closest(".outer").find("input[name*=harga]").val(hargaproduk);
});
$(document).on("blur", "input[name*=jumlah]", function() {
var jumlah = $(this).val(); //get value
var harga = $(this).closest(".outer").find("input[name*=harga]").val();
var subtotal = jumlah * harga;
//add value to subtotal
$(this).closest(".outer").find("input[name=subtotal]").val(subtotal);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container1">
<!--just added outer class-->
<div class="form-group row outer">
<div class="col-lg-3">
<select class="form-control border-teal" id="produk_nama1" name="produk_nama[]">
<option value="">Pilih Produk</option>
<option data-stok="something" data-price="12" value="1">1</option>
<option data-stok="something" data-price="13" value="2">2</option>
<option data-stok="something" data-price="14" value="3">3</option>
</select>
<div class="d-block form-text">
<span id="stok1" class="badge bg-orange"></span>
</div>
</div>
<div class="col-lg-3">
<input type="text" id="harga1" name="harga[]" class="form-control border-teal border-1" placeholder="Harga Produk" readonly>
</div>
<div class="col-lg-3">
<input type="number" id="jumlah1" name="jumlah[]" min="1" class="form-control border-teal border-1" placeholder="Masukkan Jumlah">
</div>
<div class="col-lg-3">
<input type="text" id="subtotal1" name="subtotal" class="form-control border-teal border-1" placeholder="Subtotal" readonly>
</div>
</div>
</div>
<button id="add_button">Add more</button>

How to prevent append from key in button to not add extra values when a new div is created

I've created a form which will add products to be key in details of the said products, each products will sometime have serialnumbers, users will need to click enabled serial numbers to start key in serial numbers.
So i have issue here whereby, when i add a new product, and key in serial number on product #1, it will have additional value added to it.
in a more detailed and simpler explanation;
Add Product -> product #2 created.
enabled product #1 table to key in
value inputted to textarea became
SGH983819;
;
How do i go about to not let any previous product's key in not add on those ;\n in any previous appended section?
$(document).ready(function() {
function enableSerial() {
$('.enable-serial').on('change', function() {
var item = $(this).data('item');
$('.enable-' + item).prop('disabled', !this.checked);
});
}
$('#add_product').on('click', function() {
var itemNo = $('.product-item').length + 1;
var appendData = '<div class="product-item" data-item="' + itemNo +'">' +
'<span>#' + itemNo +'</span>' +
'<button type="button" class="btn btn-danger float-right remove_product"><i class="fas fa-trash-alt"></i></button>' +
'<div class="form-group row">' +
'<label class="col-sm-2 col-form-label font-weight-bold">Category</label>' +
'<div class="col-sm-2">' +
'<input class="form-control" name="products[' + (itemNo - 1) + ']category" type="text" placeholder="eg. 333" maxlength="3"required>' +
'</div>' +
'<label class="col-sm-1 col-form-label font-weight-bold">Code</label>' +
'<div class="col-sm-2">' +
'<input class="form-control" name="products[' + (itemNo - 1) + ']code" type="text" placeholder="eg. 22" maxlength="2" required>' +
'</div>' +
'<label class="col-sm-1 col-form-label font-weight-bold">Partnumber</label>' +
'<div class="col-sm-2">' +
'<input class="form-control" name="products[' + (itemNo - 1) + ']partnumber" type="text" placeholder="eg. NGH92838" required>' +
'</div>' +
'</div>' +
'<div class="form-group row">' +
'<label class="col-sm-2 col-form-label font-weight-bold">Brand</label>' +
'<div class="col-sm-2">' +
'<input class="form-control" name="products[' + (itemNo - 1) + ']brand" type="text" placeholder="eg. Rototype" required>' +
'</div>' +
'<label class="col-sm-1 col-form-label font-weight-bold">Quantities</label>' +
'<div class="col-sm-2">' +
'<input class="form-control" name="products[' + (itemNo - 1) + ']qty" type="number" placeholder="eg. 1" required>' +
'</div>' +
'<label class="col-sm-1 col-form-label font-weight-bold">Location</label>' +
'<div class="col-sm-2">' +
'<input class="form-control location-ctrl-' + itemNo +' location-ctrl" data-item="' + itemNo +'" type="text" name="products[' + (itemNo - 1) + ']loc_name" list="locations" value="">' +
'<input type="hidden" class="location-id-' + itemNo +'" name="products[' + (itemNo - 1) + ']location_id" value="">' +
'<input type="hidden" class="loc-desc-' + itemNo +'" name="products[' + (itemNo - 1) + ']loc_desc" value="">' +
'</div>' +
'</div>' +
'<div class="form-group row">' +
'<label class="col-sm-2 col-form-label font-weight-bold">Description</label>' +
'<div class="col-sm-8">' +
'<input class="form-control" name="products[0]description" type="text" placeholder="eg. Spare part for CSD2002">' +
'</div>' +
'</div>' +
'<div class="form-group row">' +
'<label class="col-sm-2 col-form-label font-weight-bold">Serial Number(s)</label>' +
'<div class="col-sm-5">' +
'<input class="form-control enable-' + itemNo +' serial-' + itemNo +'" maxlength="25" placeholder="Key in Serial Number and hit button Key In" disabled>' +
'</div>' +
'<div class="col-sm-5">' +
'<button class="btn btn-dark enable-' + itemNo +' keyin-ctrl-' + itemNo +' keyin-ctrl" data-item="' + itemNo +'" type="button" disabled>Key In</button>' +
'<button class="btn btn-dark ml-1 enable-' + itemNo +' undo-ctrl-' + itemNo +' undo-ctrl" data-item="' + itemNo +'" type="button" disabled>Del</button>' +
'<input class="form-check-input ml-4 mt-2 pointer enable-serial-' + itemNo +' enable-serial" data-item="'+ itemNo +'" id="checkbox-' + itemNo +'" type="checkbox">' +
'<label class="form-check-label ml-5 pointer" for="checkbox-' + itemNo +'">tick to enable serialnumber</label>' +
'</div>' +
'</div>' +
'<div class="form-group row">' +
'<label class="col-sm-2 col-form-label"></label>' +
'<div class="col-sm-5">' +
'<textarea class="form-control display-' + itemNo +'" name="products[' + (itemNo - 1) + ']serialnumbers" rows="5" style="resize: none;" placeholder="eg. SGH8484848" readonly></textarea>' +
'</div>' +
'</div>' +
'<hr>' +
'</div>';
$('#append').append(appendData);
enableSerial();
ctrlSerial();
});
function ctrlSerial() {
$('.keyin-ctrl').on('click', function() {
var item = $(this).data('item');
var result = $('.serial-' + item).val() + '; \n';
$('.display-' + item).append(result);
$('.serial-' + item).val('').focus();
});
$('.undo-ctrl').on('click', function() {
var item = $(this).data('item');
$('.display-' + item).html('');
});
}
$('#append').on('click','.remove_product', function(){
var itemNo = $('.product-item').length + 1;
$(this).parent('div').remove();
itemNo--;
});
enableSerial();
ctrlSerial();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<main class="shadow border">
<h4>Product Details</h4>
<hr>
<h5>GRN Details</h5>
<form method="post" action="">
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">GRN</label>
<div class="col-sm-4">
<input class="form-control" type="text" value="020719" name="nnmmyy" readonly>
<input type="hidden" name="supp_name" value="ABCD Co. Ltd.">
<input type="hidden" name="supp_do" value="DO97/39901/01">
<input type="hidden" name="do_date" value="17/07/2019">
</div>
</div>
<!-- Multiple Product addition -->
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">Product Setting</label><br/>
<div class="col-sm-5">
<button type="button" id="add_product" class="btn btn-dark">Add Product <i class="fas fa-plus-square"></i></button>
</div>
</div>
<hr>
<!-- Frist Group -->
<div class="product" id="append">
<!-- Product Details -->
<div class="product-item" data-item="1">
<span>#1</span>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">Category</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]category" type="text" placeholder="eg. 333" maxlength="3"required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">Code</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]code" type="text" placeholder="eg. 22" maxlength="2" required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">Partnumber</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]partnumber" type="text" placeholder="eg. NGH92838" required>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">Brand</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]brand" type="text" placeholder="eg. Rototype" required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">Quantities</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]qty" type="number" placeholder="eg. 1" required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">Location</label>
<div class="col-sm-2">
<input class="form-control location-ctrl-1 location-ctrl" data-item="1" type="text" name="products[0]loc_name" list="locations" value="">
<input type="hidden" class="location_id-1" name="products[0]location_id" value="">
<input type="hidden" class="loc_desc-1" name="products[0]loc_desc" value="">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">Description</label>
<div class="col-sm-8">
<input class="form-control" name="products[0]description" type="text" placeholder="eg. Spare part for CSD2002">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">Serial Number(s)</label>
<div class="col-sm-5">
<input class="form-control enable-1 serial-1" maxlength="25" placeholder="Key in Serial Number and hit button Key In" disabled>
</div>
<div class="col-sm-5">
<button class="btn btn-dark enable-1 keyin-ctrl-1 keyin-ctrl" data-item="1" type="button" disabled>Key In</button>
<button class="btn btn-dark enable-1 undo-ctrl-1 undo-ctrl" data-item="1" type="button" disabled>Del</button>
<input class="form-check-input ml-4 mt-2 pointer enable-serial-1 enable-serial" data-item="1" id="checkbox-1" type="checkbox">
<label class="form-check-label ml-5 pointer" for="checkbox-1">tick to enable serialnumber</label>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label"></label>
<div class="col-sm-5">
<textarea class="form-control display-1" name="products[0]serialnumbers" rows="5" style="resize: none;" placeholder="eg. SGH8484848" readonly></textarea>
</div>
</div>
<hr>
</div>
<!-- append start -->
</div>
<datalist id="locations">
<option value="A0001" data-locationid="1" data-locdesc="Cabinet A"></option>
</datalist>
</form>
</main>
I in hope that there some suggestion or way to do it whereby wont have additional value added when keying previous product serial numbers
found my own fix...
added result.val(''); will reset any key in
function ctrlSerial() {
$('.keyin-ctrl').on('click', function() {
var item = $(this).data('item');
var result = $('.serial-' + item).val() + '; \n';
$('.display-' + item).append(result);
$('.serial-' + item).val('').focus();
result.val(''); // added this to also wipe clean properly
});
$('.undo-ctrl').on('click', function() {
var item = $(this).data('item');
$('.display-' + item).html('');
});
}

how to Auto Increment the value in input field (type=text) that is dynamically added on a button click?

I want to have a value in "sr.no." field that is auto incremented every time i click on button that adds new clause.
html:
<div id="clauseDiv">
<div class="col-sm-12">
<div class="col-sm-6">
<div class="form-group">
<label class="control-label col-sm-2" for="clause">Clause: </label>
<div class="col-sm-10">
<input type="text" class="form-control clauseHeader" v-bind:id="'clauseHeader-' + clause.contractGroupId"
name="clause" :key="index" v-bind:value="clause.contractGroupName" readonly="readonly"/>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label class="control-label col-sm-2" for="sequence">Sr.no.: </label>
<div class="col-sm-4">
<input type="text" class="form-control clauseSequence" v-bind:id="'clauseSequence-' + clause.contractGroupId" name="sequence"
:key="index" v-bind:value="clause.sequence" />
</div>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label class="control-label col-sm-1" for="subClause">Subclause: </label>
<div class="col-sm-11">
<div>
<textarea class="form-control subClause" v-bind:id="'subClause-' + clause.contractGroupId"
:key="index" readonly="readonly"></textarea>
</div>
</div>
</div>
</div>
</div>
js:
var clauseHtml = '<div class="col-sm-12" id="clause-'+this.count+'">'+
'<div class="col-sm-6">'+
'<div class="form-group">'+
' <label class="control-label col-sm-2" for="clause">Clause: </label>'+
' <div class="col-sm-10">'+
' <input type="text" class="form-control clauseAddlTermHeader" id="clauseHeader-'+this.count+'" name="clause" />'+
' </div>'+
' </div>'+
'</div>'+
'<div class="col-sm-4">'+
'<div class="form-group">'+
' <label class="control-label col-sm-2" for="sequence">Sr.no: </label>'+
' <div class="col-sm-4">'+
' <input type="text" class="form-control clauseAddlTermSequence" id="clauseSequence-'+this.count+'" name="sequence"/>'+
' </div>'+
' </div>'+
' </div>'+
'<div class="col-sm-2">'+
'<div class="form-group">'+
' <button type="button" class="btn btn-danger deleteClause" id="deleteClause-'+this.count+'" v-on:click="deleteClause">Delete</button>'+
' </div>'+
' </div>'+
'<div class="col-sm-12">'+
' <div class="form-group">'+
' <label class="control-label col-sm-1" for="subClause">Subclause: </label>'+
' <div class="col-sm-11">'+
' <textarea class="form-control clauseAddlTermSubClause" id="subClause-'+this.count+'" ></textarea>'+
' </div>'+
' </div>'+
' </div>'+
'</div>';
$('#clauseDiv').append(clauseHtml);
this.count++;
From html, I am adding div which contains 'clause', 'sr.no.' and 'subclause' fields. I have a button, and when clicked on that button the js part gets executed and the div appends and more 'clause', 'sr.no.' and 'subclause' fields are added. I want the newly appended 'sr.no' field to get a value in it that is auto incremented from the previous field. How do I do that?
remove this from this.count and make the count as global variable, add value="' + count +'" to the input and it should be like this
'<input type="text" class="form-control clauseAddlTermSequence" id="clauseSequence-' + count + '" name="sequence" value="' + count +'"/>'
Demo:
var count = 0;
$('#addClause').on('click', function() {
var clauseHtml = '<div class="col-sm-12" id="clause-' + count + '">' +
'<div class="col-sm-6">' +
'<div class="form-group">' +
' <label class="control-label col-sm-2" for="clause">Clause: </label>' +
' <div class="col-sm-10">' +
' <input type="text" class="form-control clauseAddlTermHeader" id="clauseHeader-' + count + '" name="clause" />' +
' </div>' +
' </div>' +
'</div>' +
'<div class="col-sm-4">' +
'<div class="form-group">' +
' <label class="control-label col-sm-2" for="sequence">Sr.no: </label>' +
' <div class="col-sm-4">' +
' <input type="text" class="form-control clauseAddlTermSequence" id="clauseSequence-' + count + '" name="sequence" value="' + count +'"/>' +
' </div>' +
' </div>' +
' </div>' +
'<div class="col-sm-2">' +
'<div class="form-group">' +
' <button type="button" class="btn btn-danger deleteClause" id="deleteClause-' + count + '" v-on:click="deleteClause">Delete</button>' +
' </div>' +
' </div>' +
'<div class="col-sm-12">' +
' <div class="form-group">' +
' <label class="control-label col-sm-1" for="subClause">Subclause: </label>' +
' <div class="col-sm-11">' +
' <textarea class="form-control clauseAddlTermSubClause" id="subClause-' + count + '" ></textarea>' +
' </div>' +
' </div>' +
' </div>' +
'</div>';
$('#clauseDiv').append(clauseHtml);
count++;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="addClause">addCaluse</button>
<div id="clauseDiv"></div>

Values are set when manual trigger change on SELECT but not when triggering from inside a function, why?

I am building some DOM elements dynamically as you may see in the snippet below. The idea is as follow:
If I change the SELECT and my choice is Yes/No then build a set of elements and insert them inside the DOM.
If I click on the button then some values should be set dynamically for those previous constructed elements
If you follow this path everything works as expected.
I would expect by clicking on the button and because the load_edit_question function is triggering a change on the SELECT to get the same results but if you click the button only those values gets undefined.
What I am missing here?
$(document).ready(function() {
var options = [{
field_id: 294249,
field_seq: 36,
field_type_id: 8,
form_id: 9926,
is_base_grid: null,
option_desc: "Yes",
option_id: 364371,
other_required: 0
}, {
field_id: 294249,
field_seq: 36,
field_type_id: 8,
form_id: 9926,
is_base_grid: null,
option_desc: "No",
option_id: 364372,
other_required: 0
}],
i = 1,
k = 1,
container_yes_no = $("#options_yes_no"),
field_type = $("#field_type_id"),
content = '<label>Options</label>\n' +
'<div id="options_yes_no">\n' +
' <div class="row-fluid">\n' +
' <div class="span2 text-center"></div>\n' +
' <div class=\'span6\'>\n' +
' <input type="text"\n' +
' class="options"\n' +
' name="option_desc[]"\n' +
' style="width:98%"\n' +
' value="Yes"\n' +
' data-option_field_id=""\n' +
' data-option_id=""\n' +
' />\n' +
' </div>\n' +
' <div class="span2">\n' +
' <label class="checkbox">\n' +
' <input type="checkbox" value="1" class="option_other_required" name="other_required[]"/> Other\n' +
' </label>\n' +
' </div>\n' +
' <div class="span2">\n' +
' <button type="button" class="btn btn-success save-option"><i class="icon-ok"></i></button>\n' +
' <button type="button" class="btn btn-danger delete-option"><i class="icon-trash"></i></button>\n' +
' </div>\n' +
' </div>\n' +
' <div class="row-fluid">\n' +
' <div class="span2 text-center"></div>\n' +
' <div class=\'span6\'>\n' +
' <input type="text"\n' +
' class="options"\n' +
' name="option_desc[]"\n' +
' style="width:98%"\n' +
' value="No"\n' +
' data-option_field_id=""\n' +
' data-option_id=""\n' +
' />\n' +
' </div>\n' +
' <div class="span2">\n' +
' <label class="checkbox">\n' +
' <input type="checkbox" value="1" class="option_other_required" name="other_required[]"/> Other\n' +
' </label>\n' +
' </div>\n' +
' <div class="span2">\n' +
' <button type="button" class="btn btn-success save-option"><i class="icon-ok"></i></button>\n' +
' <button type="button" class="btn btn-danger delete-option"><i class="icon-trash"></i></button>\n' +
' </div>\n' +
' </div>\n' +
'</div>\n';
field_type.change(function() {
var field_type_id = $(this).find('option:selected'),
field_type_name = field_type_id.data('alias');
switch (field_type_name) {
case 'yes_no':
container_yes_no.html(content);
var i = 1,
k = 1;
container_yes_no.find(":text").each(function() {
$(this).attr("id", "option_desc_" + i);
console.log("option_desc_" + i);
i++;
});
container_yes_no.find(":checkbox").each(function() {
$(this).attr("id", "option_other_" + k);
k++;
});
break;
default:
console.log(field_type_name);
break;
}
}).trigger('change');
$("#me").on("click", function() {
load_edit_question(field_type, options);
});
});
function load_edit_question(select_el, options) {
select_el.trigger('change');
loadq(options);
}
function loadq(options) {
console.log(options);
for (var i = 0; i < options.length; i++) {
var option = options[i],
curr_opt_desc = $("#option_desc_" + (i + 1)),
curr_option_other = $("#option_other_" + (i + 1)),
fullId = option.field_id + '_' + option.option_id;
curr_opt_desc.val(option.option_desc);
curr_option_other.prop('checked', option.other_required === 1);
curr_opt_desc.data("option_id", option.option_id);
curr_opt_desc.data("option_field_id", option.field_id);
console.log(fullId);
console.log(curr_opt_desc.val());
console.log(curr_opt_desc.data("option_id"));
console.log(curr_opt_desc.data("option_field_id"));
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Options</label>
<div id="options_yes_no">
<div class="row-fluid">
<div class="span2 text-center"></div>
<div class='span6'>
<input type="text" class="options" name="option_desc[]" style="width:98%" value="Yes" data-option_field_id="" data-option_id="" />
</div>
<div class="span2">
<label class="checkbox">
<input type="checkbox" value="1" class="option_other_required" name="other_required[]" /> Other
</label>
</div>
<div class="span2">
<button type="button" class="btn btn-success save-option"><i class="icon-ok"></i></button>
<button type="button" class="btn btn-danger delete-option"><i class="icon-trash"></i></button>
</div>
</div>
<div class="row-fluid">
<div class="span2 text-center"></div>
<div class='span6'>
<input type="text" class="options" name="option_desc[]" style="width:98%" value="No" data-option_field_id="" data-option_id="" />
</div>
<div class="span2">
<label class="checkbox">
<input type="checkbox" value="1" class="option_other_required" name="other_required[]" /> Other
</label>
</div>
<div class="span2">
<button type="button" class="btn btn-success save-option"><i class="icon-ok"></i></button>
<button type="button" class="btn btn-danger delete-option"><i class="icon-trash"></i></button>
</div>
</div>
</div>
<select id="field_type_id" name="field_type_id" class="span12">
<option value="">Select One</option>
<option value="2" data-alias="checkbox">Checkbox</option>
<option value="3" data-alias="date">Date</option>
<option value="5" data-alias="fixed_text">Fixed Text</option>
<option value="1" data-alias="radio">Radio</option>
<option value="4" data-alias="text">Text</option>
<option value="6" data-alias="textarea">Textarea</option>
<option value="8" data-alias="yes_no">Yes/No</option>
</select>
<button id="me"> Click me</button>
PS: if the snippet does not work properly I have setup a Fiddle also here
While you click the button, you didn't set the value before you trigger the event, which will leave the selected option to be blank, and then run the default routine in your switch action. Thus none of the input values are actually being set, and you got undefined when trying to print them.
$(document).ready(function() {
var options = [{
field_id: 294249,
field_seq: 36,
field_type_id: 8,
form_id: 9926,
is_base_grid: null,
option_desc: "Yes",
option_id: 364371,
other_required: 0
}, {
field_id: 294249,
field_seq: 36,
field_type_id: 8,
form_id: 9926,
is_base_grid: null,
option_desc: "No",
option_id: 364372,
other_required: 0
}],
i = 1,
k = 1,
container_yes_no = $("#options_yes_no"),
field_type = $("#field_type_id"),
content = '<label>Options</label>\n' +
'<div id="options_yes_no">\n' +
' <div class="row-fluid">\n' +
' <div class="span2 text-center"></div>\n' +
' <div class=\'span6\'>\n' +
' <input type="text"\n' +
' class="options"\n' +
' name="option_desc[]"\n' +
' style="width:98%"\n' +
' value="Yes"\n' +
' data-option_field_id=""\n' +
' data-option_id=""\n' +
' />\n' +
' </div>\n' +
' <div class="span2">\n' +
' <label class="checkbox">\n' +
' <input type="checkbox" value="1" class="option_other_required" name="other_required[]"/> Other\n' +
' </label>\n' +
' </div>\n' +
' <div class="span2">\n' +
' <button type="button" class="btn btn-success save-option"><i class="icon-ok"></i></button>\n' +
' <button type="button" class="btn btn-danger delete-option"><i class="icon-trash"></i></button>\n' +
' </div>\n' +
' </div>\n' +
' <div class="row-fluid">\n' +
' <div class="span2 text-center"></div>\n' +
' <div class=\'span6\'>\n' +
' <input type="text"\n' +
' class="options"\n' +
' name="option_desc[]"\n' +
' style="width:98%"\n' +
' value="No"\n' +
' data-option_field_id=""\n' +
' data-option_id=""\n' +
' />\n' +
' </div>\n' +
' <div class="span2">\n' +
' <label class="checkbox">\n' +
' <input type="checkbox" value="1" class="option_other_required" name="other_required[]"/> Other\n' +
' </label>\n' +
' </div>\n' +
' <div class="span2">\n' +
' <button type="button" class="btn btn-success save-option"><i class="icon-ok"></i></button>\n' +
' <button type="button" class="btn btn-danger delete-option"><i class="icon-trash"></i></button>\n' +
' </div>\n' +
' </div>\n' +
'</div>\n';
field_type.change(function() {
var field_type_id = $(this).find('option:selected'),
field_type_name = field_type_id.data('alias');
switch (field_type_name) {
case 'yes_no':
container_yes_no.html(content);
var i = 1,
k = 1;
container_yes_no.find(":text").each(function() {
$(this).attr("id", "option_desc_" + i);
console.log("option_desc_" + i);
i++;
});
container_yes_no.find(":checkbox").each(function() {
$(this).attr("id", "option_other_" + k);
k++;
});
break;
default:
console.log(field_type_name);
break;
}
}).trigger('change');
$("#me").on("click", function() {
load_edit_question(field_type, options);
});
});
function load_edit_question(select_el, options) {
select_el.val('8').trigger('change');
loadq(options);
}
function loadq(options) {
console.log(options);
for (var i = 0; i < options.length; i++) {
var option = options[i],
curr_opt_desc = $("#option_desc_" + (i + 1)),
curr_option_other = $("#option_other_" + (i + 1)),
fullId = option.field_id + '_' + option.option_id;
curr_opt_desc.val(option.option_desc);
curr_option_other.prop('checked', option.other_required === 1);
curr_opt_desc.data("option_id", option.option_id);
curr_opt_desc.data("option_field_id", option.field_id);
console.log(fullId);
console.log(curr_opt_desc.val());
console.log(curr_opt_desc.data("option_id"));
console.log(curr_opt_desc.data("option_field_id"));
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Options</label>
<div id="options_yes_no">
<div class="row-fluid">
<div class="span2 text-center"></div>
<div class='span6'>
<input type="text" class="options" name="option_desc[]" style="width:98%" value="Yes" data-option_field_id="" data-option_id="" />
</div>
<div class="span2">
<label class="checkbox">
<input type="checkbox" value="1" class="option_other_required" name="other_required[]" /> Other
</label>
</div>
<div class="span2">
<button type="button" class="btn btn-success save-option"><i class="icon-ok"></i></button>
<button type="button" class="btn btn-danger delete-option"><i class="icon-trash"></i></button>
</div>
</div>
<div class="row-fluid">
<div class="span2 text-center"></div>
<div class='span6'>
<input type="text" class="options" name="option_desc[]" style="width:98%" value="No" data-option_field_id="" data-option_id="" />
</div>
<div class="span2">
<label class="checkbox">
<input type="checkbox" value="1" class="option_other_required" name="other_required[]" /> Other
</label>
</div>
<div class="span2">
<button type="button" class="btn btn-success save-option"><i class="icon-ok"></i></button>
<button type="button" class="btn btn-danger delete-option"><i class="icon-trash"></i></button>
</div>
</div>
</div>
<select id="field_type_id" name="field_type_id" class="span12">
<option value="">Select One</option>
<option value="2" data-alias="checkbox">Checkbox</option>
<option value="3" data-alias="date">Date</option>
<option value="5" data-alias="fixed_text">Fixed Text</option>
<option value="1" data-alias="radio">Radio</option>
<option value="4" data-alias="text">Text</option>
<option value="6" data-alias="textarea">Textarea</option>
<option value="8" data-alias="yes_no">Yes/No</option>
</select>
<button id="me"> Click me</button>

Categories

Resources