generate dynamic div and retrieve value of input elements - javascript

I am having div with input elements with Add and Cancel buttons.
When user clicked on add Button,I need to generate div with the same input elements and capture the value to JSon object.
Here is my code snippet
<div id="filterfields" class="row collapse">
<form class="form-inline" id="filterFieldsForm">
<select class="form-control" name="TypeCode" id="filterType_0">
<option value="Type">Type</option>
<option value="SubmittedBy">SubmittedBy</option>
<option value="Date">Date</option>
<option value="Description">Description</option>
</select>
<select class="form-control" name="Filter" id="filterCondition_0">
<option value="Equal">Equal</option>
<option value="StartsWith">Starts With</option>
<option value="EndsWith">Ends With</option>
<option value="Greaterthan">Greater Than</option>
<option value="Lessthan">Less Than</option>
</select>
<input type="text" name="caseFilterText" class="form-control" id="filterText_0">
<input class="form-control" type="radio" name="inlineRadioOptions" id="andRadio_0" value="AND">
<label for="andRadio">AND</label>
<input class="form-control" type="radio" name="inlineRadioOptions" id="orRadio_0" value="OR">
<label for="orRadio">OR</label>
<button id="addBtn_0" type="button" class="btn btn-secondary">Add</button>
<button id="cancelBtn_0" type="button" class="btn btn-secondary">Cancel</button>
</form>
</div>
I tried with clone and trying to retrieve values from the input elements inside div,but I am facing issue with getting values and generating ids.
$('#addBtn_' + count).click(function () {
var newel = $("#filterfields").clone(true);
var jsonData = [];
$(newel).insertAfter("#filterfields");
var index;
$("#filterfields").find('input:text,select').each(function () {
let str = '{"' + this.id + '":' + (this.value + '}';
jsonData.push(str);
}).end()
newel.find(':input').each(function () {
var oldId = $(this).attr("id");
var split = oldId.toString().split('_');
index = parseInt(split[1]);
var curId = split[0];
var newId = curId + "_" + index + 1;
this.id = newId;
}).end()
jsonData.push('"filterClause":' + $('input[name="inlineRadioOptions"]:checked').val() + '"');
});
Please suggest me if there is better way to achieve the similar function as I am not able to get values of input elements of current row.

Consider the following code.
$(function() {
function formToJson(fObj) {
var j = [];
fObj.children().not("button, label").each(function(i, el) {
// Will avoid buttons and labels
if (!($(el).is(":radio") && !$(el).is(":checked"))) {
// Will avoid unselected Radio Buttons
var d = {
nodeName: $(el).prop("nodeName"),
props: {
class: $(el).attr("class"),
id: $(el).attr("id")
},
value: $(el).val(),
name: $(el).attr("name")
};
if (d.nodeName != "SELECT") {
d.props.type = $(el).attr("type");
}
j.push(d);
}
});
return j;
}
$("[id^='addBtn']").click(function() {
var jsonData = formToJson($("#filterFieldsForm"));
console.log(jsonData);
var filter = "Filter: ";
$.each(jsonData, function(key, item) {
if (key != 2) {
filter += item.value + " ";
} else {
filter += "'" + item.value + "' ";
}
});
$("<div>", {
class: "filter-results"
}).html(filter).appendTo("body");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="filterfields" class="row collapse">
<form class="form-inline" id="filterFieldsForm">
<select class="form-control" name="TypeCode" id="filterType_0">
<option value="Type">Type</option>
<option value="SubmittedBy">SubmittedBy</option>
<option value="Date">Date</option>
<option value="Description">Description</option>
</select>
<select class="form-control" name="Filter" id="filterCondition_0">
<option value="Equal">Equal</option>
<option value="StartsWith">Starts With</option>
<option value="EndsWith">Ends With</option>
<option value="Greaterthan">Greater Than</option>
<option value="Lessthan">Less Than</option>
</select>
<input type="text" name="caseFilterText" class="form-control" id="filterText_0">
<input class="form-control" type="radio" name="inlineRadioOptions" id="andRadio_0" value="AND">
<label for="andRadio">AND</label>
<input class="form-control" type="radio" name="inlineRadioOptions" id="orRadio_0" value="OR">
<label for="orRadio">OR</label>
<button id="addBtn_0" type="button" class="btn btn-secondary">Add</button>
<button id="cancelBtn_0" type="button" class="btn btn-secondary">Cancel</button>
</form>
</div>
As you are iterating over elements, it is best to use .each(). Using the proper selector, we can target just the form elements you want. You then want a condition to ensure that if a Radio Button is selected (or checked) that it is included and others are excluded.
The result is an Array of Objects that can be used to rebuild the HTML Structure or just build new copies.
Update
$(function() {
function formToJson(fObj) {
var j = [];
fObj.each(function(i, el) {
var d = {};
$("select, input", el).each(function(k, v) {
if (!($(v).is(":radio") && !$(v).is(":checked"))) {
d[$(v).attr("id")] = $(v).val();
}
});
j.push(d);
});
return j;
}
$("[id^='addBtn']").click(function() {
var jsonData = formToJson($("#filterFieldsForm"));
console.log(jsonData);
var filter = "Filter: ";
$.each(jsonData, function(key, item) {
if (key != 2) {
filter += item.value + " ";
} else {
filter += "'" + item.value + "' ";
}
});
$("<div>", {
class: "filter-results"
}).html(filter).appendTo("body");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="filterfields" class="row collapse">
<form class="form-inline" id="filterFieldsForm">
<select class="form-control" name="TypeCode" id="filterType_0">
<option value="Type">Type</option>
<option value="SubmittedBy">SubmittedBy</option>
<option value="Date">Date</option>
<option value="Description">Description</option>
</select>
<select class="form-control" name="Filter" id="filterCondition_0">
<option value="Equal">Equal</option>
<option value="StartsWith">Starts With</option>
<option value="EndsWith">Ends With</option>
<option value="Greaterthan">Greater Than</option>
<option value="Lessthan">Less Than</option>
</select>
<input type="text" name="caseFilterText" class="form-control" id="filterText_0">
<input class="form-control" type="radio" name="inlineRadioOptions" id="andRadio_0" value="AND">
<label for="andRadio">AND</label>
<input class="form-control" type="radio" name="inlineRadioOptions" id="orRadio_0" value="OR">
<label for="orRadio">OR</label>
<button id="addBtn_0" type="button" class="btn btn-secondary">Add</button>
<button id="cancelBtn_0" type="button" class="btn btn-secondary">Cancel</button>
</form>
</div>
This will target the various rows and for each row, it will gather all the Select and Inputs.

Related

HTML Dropdown filter based on another dropdown selection

I tried dropdown filter based on another dropdown,
It's working If I don't use space in the value in option.
If I use space in value, then it's not working.
$("#Type").on("change", function() {
var values = $(this).val().split(',', ) //split value which is selected
$("#fruits option").hide() //hide all options from slect box
//loop through values
for (var i = 0; i < values.length; i++) {
var vals = values[i]
$("#fruits option[value=" + vals + "]").show() //show that option
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-row last">
<div class="form-wrapper">
<label for="">Department</label>
<select id="Type" name="Type" class='form-control'>
<option disabled="disabled" selected="selected">Choose option</option>
<option value='Apple'>Diet 1</option>
<option value='Red Banana,Green Apple'>Diet 2</option>
</select>
<i class="zmdi zmdi-chevron-down"></i>
</div>
<div class="form-wrapper">
<label for="">Device</label>
<select id="fruits" name="fruits" class='form-control'>
<option disabled="disabled" selected="selected">Choose option</option>
<option value='Apple'>Apple</option>
<option value='Red Banana'>Banana</option>
<option value='Green Apple'>G Apple</option>
</select>
<i class="zmdi zmdi-chevron-down"></i>
</div>
</div>
Here If I select Apple value - Diet 1, it's working.
If I select Diet 2, it should show Banana and G Apple in second drop down.
Please help me how to get the Red Banana value from 1st dropdown and filter the second dropdown,
You weren't far off you just missing closing single quotation marts in this line:
before:
$("#fruits option[value=" + vals + "]").show() /
after
$("#fruits option[value='" + vals + "']").show() /
$("#Type").on("change", function() {
debugger
var values = $(this).val().split(',', ) //split value which is selected
$("#fruits option").hide() //hide all options from slect box
//loop through values
for (var i = 0; i < values.length; i++) {
var vals = values[i]
$("#fruits option[value='" + vals + "']").show() //show that option
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-row last">
<div class="form-wrapper">
<label for="">Department</label>
<select id="Type" name="Type" class='form-control'>
<option disabled="disabled" selected="selected">Choose option</option>
<option value='Apple'>Diet 1</option>
<option value='Red Banana,Green Apple'>Diet 2</option>
</select>
<i class="zmdi zmdi-chevron-down"></i>
</div>
<div class="form-wrapper">
<label for="">Device</label>
<select id="fruits" name="fruits" class='form-control'>
<option disabled="disabled" selected="selected">Choose option</option>
<option value='Apple'>Apple</option>
<option value='Red Banana'>Banana</option>
<option value='Green Apple'>G Apple</option>
</select>
<i class="zmdi zmdi-chevron-down"></i>
</div>
</div>
I hope this helps
Biased on you follow up question here is an example of the second drop down bound to an array instead of being hard coded
var data = [{
'value': 'Apple',
'product': 'Green Apple'
}, {
'value': 'Grape',
'product': 'Fresh Grape'
}];
$(function() {
$.each(data, function(index, itemData) {
$('#fruits').append($("<option></option>")
.attr("value", itemData.product)
.text(itemData.value));
});
})
$("#Type").on("change", function() {
var values = $(this).val().split(',', ) //split value which is selected
$("#fruits option").hide() //hide all options from slect box
//loop through values
for (var i = 0; i < values.length; i++) {
var vals = values[i]
$("#fruits option[value='" + vals + "']").show() //show that option
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-row last">
<div class="form-wrapper">
<label for="">Department</label>
<select id="Type" name="Type" class='form-control'>
<option disabled="disabled" selected="selected">Choose option</option>
<option value='Fresh Grape'>Diet 1</option>
<option value='Blue Apple,Green Apple'>Diet 2</option>
</select>
<i class="zmdi zmdi-chevron-down"></i>
</div>
<div class="form-wrapper">
<label for="">Device</label>
<select id="fruits" name="fruits" class='form-control'>
<option disabled="disabled" selected="selected">Choose option</option>
</select>
<i class="zmdi zmdi-chevron-down"></i>
</div>
</div>
I hope this helps

How to combine Selected price and input checkbox price Jquery?

i have a checkout form . where there are 2 fields are used o give total amount of checkout . 1 field is in select tag and second is input type check box i want when i select and option and checkbox there values should be combine to give total.
$(function() {
$('.price-input').change(function() {
var price = 0;
$('.price-input').each(function() {
if ($(this).is(":checked")) {
price += parseInt($(this).attr("value"), 10);
}
})
$("select.price").change(function() {
var selectedPrice = $(this).children("option:selected").val();
document.getElementById("totalPrice").innerHTML = selectedPrice;
});
$(".totalPrice").text(price);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-6">
<div class="form-group">
<label for="exampleFormControlSelect1">#lang('Number of Words'):</label>
<select class="price" name="word_prices_id" required>
<option value="">#lang('Select Words')</option>
#foreach($wordPrice as $wPrice)
<option value="{{$wPrice->id}}">{{$wPrice->page_quantity}} words</option>
#endforeach
</select>
</div>
</div>
<input class="price-input" type="checkbox" name="upsell" value="12">
I added a class .ajx to both Select and input to handle changes made on both of their values in the same function !
$(document).on('change', '.ajx', function () {
if ($( "input.price-input:checked" ).is(":checked") && $("select.price").val()!==''){
var price = 0;
price += parseInt($("select.price").val(),10);
$('.price-input').each(function() {
if ($(this).is(":checked")) {
price += parseInt($(this).attr("value"), 10);
}
});
$(".totalPrice").empty().text(price);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-6">
<div class="form-group">
<label for="exampleFormControlSelect1">Price:</label>
<select class="price ajx" name="word_prices_id" required id="exampleFormControlSelect1">
<option value="">Choose Price</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
</div>
<input class="price-input ajx" type="checkbox" name="upsell" value="12">
<input class="price-input ajx" type="checkbox" name="upsell1" value="15">
<div class="totalPrice">
</div>

Sortable not changing ids

I want to be able, when I drag and drop, to replace all ids by the other.
For example in this code :
<div class="container">
<div class="row" id="row_0">
<div class="col-md-12">
<form id="form_0" onsubmit="return false;">
<select class="select2" name="test1" id="test1_0">
<option value="o_test">o_test1_1</option>
<option value="o_test">o_test1_2</option>
<option value="o_test">o_test1_3</option>
</select>
<select class="select2" name="test2" id="test2_0">
<option value="o_test">o_test2_1</option>
<option value="o_test">o_test2_2</option>
<option value="o_test">o_test2_3</option>
</select>
<button onclick="addRow()">clone</button>
</form>
</div>
</div>
<div class="row" id="row_1">
<div class="col-md-12">
<form id="form_1" onsubmit="return false;">
<select class="select2" name="test1" id="test1_1">
<option value="o_test">o_test1_1</option>
<option value="o_test">o_test1_2</option>
<option value="o_test">o_test1_3</option>
</select>
<select class="select2" name="test2" id="test2_1">
<option value="o_test">o_test2_1</option>
<option value="o_test">o_test2_2</option>
<option value="o_test">o_test2_3</option>
</select>
<button onclick="addRow()">clone</button>
</form>
</div>
</div>
</div>
I want to be able to change when I drag and drop all id="form_0" <-> id="form_1",id="row_0" <-> id="row_1", id="test1_0" <-> id="test1_1" .. etc, this is just an example, there are more.
I know that we can use the stop option like so :
$('.container').sortable({
stop: function(event, ui) {
var moved = ui.item,
replaced = ui.item.prev();
if (replaced.length == 0) {
replaced = ui.item.next();
}
var moved_num = parseInt(moved.attr("id").match(/\d+/g), 10) + 1;
var replaced_num = parseInt(replaced.attr("id").match(/\d+/g), 10) + 1;
moved.find('[id]').each(function() {
var $this = $(this),
split = $this.prop('id').split('_')[0];
$this.prop('id', $this.prop('id').split('_')[0] + '_' + replaced_num);
});
replaced.find('[id]').each(function() {
var $this = $(this),
split = $this.prop('id').split('_')[0];
$this.prop('id', $this.prop('id').split('_')[0] + '_' + moved_num);
});
}
});
The idea here in the code above, is to get the id number of the one moved and replaced, and for each id, replace in each one of them the number of the other.
But it doesn't do what I'm trying to do. Any idea why?
Fiddle : https://jsfiddle.net/763opz0c/
My suggestion is loop through all items and use their index within the container to update all id's
$('.container').sortable({
stop: function(event, ui) {
var $items = $(ui.item).parent().children()
$items.each(function(index){
$(this).find('[id]').add(this).attr('id', function(){
return this.id.split('_')[0] +'_' + index
});
});
}
});
Fiddle demo

Dynamically generate textbox when user enters something

Initially i have one textbox/selectbox when user enters something or selects something generate another textbox/selectbox and also i can set limit how many textbox/selectbox can be generated.
please advice me how can i achieve this
You can use jQuery append() method to create html dynamically.
$("#ddlOptions").on("change", function(e) {
var len = $('.txtInput').length;
if (len == 0) {
$('.container').append('<br> <input type="text" id=txtTextBox_' + len + ' class="txtInput" /> <br>');
}
});
$(document).on("change", '.txtInput', function() {
var len = $('.txtInput').length;
if ($(this).val() != "") {
$('.container').append('<br> <input type="text" id=txtTextBox_' + len + ' class="txtInput" /> <br>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<select id="ddlOptions">
<option>option 1</option>
<option>option 2</option>
<option>option 3</option>
<option>option 4</option>
</select>
</div>
var counter=0;
function generate(){
var newTxt='<input type="text">';
var newSel='<select><option value="">--select--</option></select>';
var txtlimit=document.getElementById('txtlimit');
var div=document.getElementById('newCtrls');
var totalElem=div.getElementsByTagName('input').length;
if(!isNaN(txtlimit.value) && txtlimit.value!=''){
if(parseInt(txtlimit.value)>counter &&
parseInt(txtlimit.value)>totalElem){
div.innerHTML += newTxt + newSel+'<br>';
counter++;
}
}else{
div.innerHTML +=newTxt + newSel+'<br>';
}
}
<input type="text" id="txtlimit" placeholder="Enter Limit"><br>
<input type="text" onkeyup="generate();">
<select onchange="generate();">
<option value="Item1">--select--</option>
<option value="Item1">Item1</option>
<option value="Item2">Item2</option>
<option value="Item3">Item3</option>
</select><br>
<div id="newCtrls">
<h3>Dynamic Controls Here</h3>
</div>

How to display selected checkboxes' values in select dropdown?

here's the jsfiddle : https://jsfiddle.net/a1gsgh11/9/
For some reason , the javascript not working in js fiddle. My concern is, when I select multiple checkboxes, the values displays correctly and immediately without having to submit any button.
How do I display these selected values inside the box that currently listed out all the programming languages?
How do I alter below script into what I want?
function moveAll(from, to) {
$('#'+from+' option').remove().appendTo('#'+to);
}
function moveSelected(from, to) {
$('#'+from+' option:selected').remove().appendTo('#'+to);
}
function selectAll() {
$("select option").attr("selected","selected");
}
I want to display the selected checkboxes values inside select dropdown below:
<form name="selection" method="post" onSubmit="return selectAll()">
<select multiple size="10" id="from">
<option value="html">Html</option>
<option value="css">Css</option>
<option value="google">Google</option>
<option value="javascript">Javascript</option>
<option value="jquery">Jquery</option>
<option value="regex">Regex</option>
<option value="php">Php</option>
<option value="mysql">Mysql</option>
<option value="xml">Xml</option>
<option value="json">Json</option>
</select>
<div class="controls">
>>
>
<
<< </div>
<select multiple id="to" size="10" name="topics[]"></select>
<form>
this line displays all the values selected in the checkboxes:
<output>0 are checked<p>No Values</p></output>
Any help appreciated.. Thanks in advance.
Please see the fiddle, it is working fine now: https://jsfiddle.net/a1gsgh11/16/
I change the way the events were called:
$(".moveAll1").click(function(){
$('#from option').remove().appendTo($('#to'));
});
$(".moveAll2").click(function(){
$('#to option').remove().appendTo($('#from'));
});
$(".moveSelected1").click(function(){
$('#from option:selected').remove().appendTo('#to');
});
$(".moveSelected2").click(function(){
$('#to option:selected').remove().appendTo('#to');
});
var checked, checkedValues = new Array();
$("input[type=checkbox]").change(function(e) {
var selectedtext = ($(this).next().text());
if($(this).is(':checked'))
{
$("#from").append('<option value="' + selectedtext + '">' + selectedtext +'</option>');
}else{
$('option[value*="' + selectedtext + '"]').remove();
}
});
Html :
<input type="checkbox" name="level" id="level" value="1"><label>Primary</label><br/>
<input type="checkbox" name="level" id="level" value="2"><label>Upper Secondary</label><br/>
<input type="checkbox" name="level" id="level" value="3"><label>University</label><br/>
</div>
<div class="small-12 medium-6 large-6 columns">
<input type="checkbox" name="level" id="level" value="4"><label>Lower Secondary</label><br/>
<input type="checkbox" name="level" id="level" value="5"><label>Pre University</label><br/>
<input type="checkbox" name="level" id="level" value="6"><label>Skills/Languages</label><br/>
<div class="controls">
<a class="moveAll1">>></a>
<a class="moveSelected1">></a>
<a class="moveSelected2"><</a>
<a class="moveAll2" href="#"><<</a>
</div>
Is this the behavior you wanted?
var ele = $(this);
var from = $('select#from');
if (ele.prop('checked')) {
var opt = $("<option></option>")
.attr("value", ele.val())
.attr('id', 'op' + ele.val())
.text(ele.val());
from.append(opt);
} else {
var opt = $('#op' + ele.val());
opt.remove();
}
fiddle

Categories

Resources