I have a dynamic form where you can click a button and a new form row is added to the form. The form entry looks like this:
<input type='text' class='custom' data-index='".$f."' name='column_value_one' value='1'>
<input type='text' class='custom' data-index='".$f."' name='column_value_two' value='2'>
For example, I add 3 lines of the above and data-index is 0 through 3. I try to process it by doing the following:
var data = [];
$(".custom").each(function() {
var index = parseInt($(this).attr('data-index'));
data[index][$(this).attr("name")] = $(this).val();
});
I am trying to have an end result of:
data[0]['column_value_one'] = 1;
data[0]['column_value_two'] = 2;
data[1]['column_value_one'] = 1;
data[1]['column_value_two'] = 2;
I only usually write PHP, hence me laying out the array as per above. But this would be a Javascript/Jquery array not PHP.
I would appreciate any help here.
You need to init the data[index] to {} if the index does not exist.
data[index] = data[index] || {};
Like:
var data = [];
$(".custom").each(function() {
var index = parseInt($(this).attr('data-index'));
data[index] = data[index] || {};
data[index][$(this).attr("name")] = $(this).val();
});
console.log(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='custom' data-index='0' name='column_value_one' value='1'>
<input type='text' class='custom' data-index='0' name='column_value_two' value='2'>
<input type='text' class='custom' data-index='1' name='column_value_one' value='1'>
<input type='text' class='custom' data-index='1' name='column_value_two' value='2'>
<input type='text' class='custom' data-index='2' name='column_value_one' value='1'>
<input type='text' class='custom' data-index='2' name='column_value_two' value='2'>
It sounds like you want an array of objects:
data = [
{column_value_one: 1, column_value_two: 2},
// ...
];
In that case, since the second input follows the first, you could do:
var data = $("input[name=column_value_one]").map(function() {
return {column_value_one: this.value, column_value_two: $(this).next().val()};
}).get();
Live Example:
var data = $("input[name=column_value_one]").map(function() {
return {column_value_one: this.value, column_value_two: $(this).next().val()};
}).get();
console.log(data);
<input type='text' class='custom' data-index='0' name='column_value_one' value='11'>
<input type='text' class='custom' data-index='0' name='column_value_two' value='12'>
<input type='text' class='custom' data-index='1' name='column_value_one' value='21'>
<input type='text' class='custom' data-index='1' name='column_value_two' value='22'>
<input type='text' class='custom' data-index='2' name='column_value_one' value='31'>
<input type='text' class='custom' data-index='2' name='column_value_two' value='32'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Or if you may have something in-between them, use two jQuery objects:
var ones = $("input[name=column_value_one]");
var twos = $("input[name=column_value_two]");
var data = ones.map(function(index) {
return {column_value_one: this.value, column_value_two: twos.eq(index).val()};
}).get();
var ones = $("input[name=column_value_one]");
var twos = $("input[name=column_value_two]");
var data = ones.map(function(index) {
return {column_value_one: this.value, column_value_two: twos.eq(index).val()};
}).get();
console.log(data);
<input type='text' class='custom' data-index='0' name='column_value_one' value='11'>
<input type='text' class='custom' data-index='0' name='column_value_two' value='12'>
<input type='text' class='custom' data-index='1' name='column_value_one' value='21'>
<input type='text' class='custom' data-index='1' name='column_value_two' value='22'>
<input type='text' class='custom' data-index='2' name='column_value_one' value='31'>
<input type='text' class='custom' data-index='2' name='column_value_two' value='32'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
In both cases, there's no need for data-index (for this; maybe you need it for something else).
Related
On my website the amount value is based on user's Radio Button choice.
Users can also enter a bigger amount than the one proposed, so the minimum amount has to be dynamically checked.
With JQuery Validation Engine, I would like to set this value:
integer[min[xx]]
Here is the code:
<script>
jQuery(document).ready(function($) {
$('#id1').click(function(){
document.getElementById('amount').value = 50;
});
$('#id2').click(function(){
document.getElementById('amount').value = 17;
});
});
</script>
HTML:
<label class='label-radio'>
<input type='radio' name='invoice' id='id1' value='id1'>
Choice 1
</label>
<label class='label-radio'>
<input type='radio' name='invoice' id='id2' value='id2'>
Choice 2
</label>
<label for='amount'>Amount
<input id='amount' name='amount' type='text' class='validate[required,integer[min[xx]]]'>
</label>
You can see a basic pattern of the source code here: Codepen
Is it possible to do this with JQuery?
Thanks for your help.
For this you need to add dynamic rule, you can see working example here
https://jsfiddle.net/dipmala/x163rbwk/15/
HTML Code
<form name="myForm">
<label class='label-radio'>
<input type='radio' name='invoice' id='id1' class='radioclick' data-val='50' value='id1'>
Choice 1
</label>
<label class='label-radio'>
<input type='radio' name='invoice' id='id2' class='radioclick' data-val='17' value='id2'>
Choice 2
</label>
<label for='amount'>Amount
<input id='amount' name='amount' type='text' >
<input type="submit">
</form>
Javascript code
$("form").validate({
rules: {
amount: {required: true, min: 1}
} });
$('.radioclick').click(function(){
var mx = parseInt($(this).attr("data-val"));
$("#amount").rules("add", {
min: mx
});
});
Maybe there is a better/cleaner way, but it works:
Javascript code
var $total;
jQuery(document).ready(function($) {
$(function() {
var $signupForm = $( '#PaypalDiv' );
$signupForm.validationEngine();
});
$('#id1').click(function(){
$total= 50;
document.getElementById('amount').value = $total;
});
$('#id2').click(function(){
$total = 17;
document.getElementById('amount').value = $total;
});
});
function check_min(field, options){
if(parseFloat(field.val()) < $total ){
return "Cannot be lower than "+$total;
}
}
HTML code
<form action='#' method='post' id='PaypalDiv'>
<label class='label-radio'>
<input type='radio' name='invoice' id='id1' value='id1'>
Choice 1
</label>
<label class='label-radio'>
<input type='radio' name='invoice' id='id2' value='id2'>
Choice 2
</label>
<label for='amount'>Amount
<input id='amount' name='amount' type='text' class='validate[required,custom[number],funcCall[check_min[amount]]]'>
</label>
<input type="submit">
</form>
I have written below code to get a total count of Checked chechbox and save the value checked value comma separated in textbox.
HTML:
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='1' onchange='checkCount(this.value);'></label>
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='2' onchange='checkCount(this.value);'></label>
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='3' onchange='checkCount(this.value);'></label>
<input type="text" name="proId" id="proId">
JS:
function checkCount(elm) {
var cheCount = $(":checkbox:checked").length;
document.getElementById('selectCount').innerHTML = cheCount;
definVal = document.getElementById('proId').value ;
var inval = elm+","+definVal;
document.getElementById('proId').value = inval;
if(cheCount==0){
document.getElementById('proId').value = "";
}
}
Check the output in below image:
My issue is that, when i unchecked the checkbox, its value is adding in textbox instead of getting remove.
Make below changes, just call js method dont send its value
And then check by their classname
function checkCount(elm) {
var checkboxes = document.getElementsByClassName("checkbox-btn");
var selected = [];
for (var i = 0; i < checkboxes.length; ++i) {
if(checkboxes[i].checked){
selected.push(checkboxes[i].value);
}
}
document.getElementById("proId").value = selected.join();
document.getElementById("total").innerHTML = selected.length;
}
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='1' onchange='checkCount();'></label>
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='2' onchange='checkCount();'></label>
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='3' onchange='checkCount();'></label>
<input type="text" name="proId" id="proId">
<div>Total Selected : <span id="total">0</span></div>
I want to concatenate two or more text box values in one text box.Here I am getting values using id but that id will be dynamically added it means text box will dynamically added.For dynamically adding text box I am using for loop but am getting the value only the last text box value only becaues for loop executed.I want all text box values.Please help me to get me out.Thank you in advance.
Here is the code for dynamic text box process:
In this am using printwriter object in servlet
int nums=5;
out.println("<input type='text' id='static'>");
int i;
for (i=0;i<nums; i++) {
out.println("<input type='text' Style='width:30px' maxlength='1' id='id"+i+"'onkeyup='sum();'> ");
out.println("<script>function sum(){ alert('id"+i+"'); var txtFirstNumberValue=document.getElementById('id'+i+'').value;var result = document.getElementById('static').value + txtFirstNumberValue;alert(result);if (isNaN(result)){ document.getElementById('static').value = result; }}</script>");
}
but if I use static text box I am getting what I need but I need that in dynamic process.
here is the code for static text box process:
<input type="text" maxlength="1" id="1" onkeyup="sum();"/>
<input type="text" maxlength="1" id="2" onkeyup="sum();"/>
<input type="text" maxlength="1" id="3" onkeyup="sum();"/>
<input type="text" id="4"/>
function sum() {
var txtFirstNumberValue = document.getElementById('1').value;
var txtSecondNumberValue = document.getElementById('2').value;
var txtThirdNumberValue = document.getElementById('3').value;
var result = txtFirstNumberValue + txtSecondNumberValue + txtThirdNumberValue;
if (isNaN(result)) {
document.getElementById('4').value = result;
}
}
Please help me to find out the solution.Thank you in advance.
I would not use inline JavaScript and I would give my elements proper IDs if I really need them otherwise I would use classes.
$(document).ready(function() {
$('.in').on('input',function() {
var allvals = $('.in').map(function() {
return this.value;
}).get().join('');
$('.out').val( allvals );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="in" type="text" maxlength="1" id="i1"/>
<input class="in" type="text" maxlength="1" id="i2"/>
<input class="in" type="text" maxlength="1" id="i3"/>
<input class="out" type="text" id="i4"/>
<script type="text/javascript">
$(document).ready(function(){
var cls = document.getElementsByClassName('test');
var i =0;
var len = cls.length;
var tot = 0;
for(i=0;i<l;i++){
var cur = cls[i].value;
tot = parseInt(cur)+tot;
}
//document.getElementById("id"+cls.length).value = tot; //set the value for last element as the tot var
});
</script>
<body>
<input type="text" maxlength="1" value="1" id="1" class="test"/>
<input type="text" maxlength="1" value="2" id="2" class="test"/>
<input type="text" maxlength="1" value="3" id="3" class="test"/>
</body>
$(document).ready(function() {
$('.in').on('input',function() {
var allvals = $('.in').map(function() { return this.value; }).get().join('');
$('.out').val( allvals );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="in" type="text" maxlength="1" id="i1"/>
<input class="in" type="text" maxlength="1" id="i2"/>
<input class="in" type="text" maxlength="1" id="i3"/>
<input class="out" type="text" id="i4"/>
$(document).ready(function() {
$('.in').on('input',function() {
var allvals = $('.in').map(function() {
return this.value;
}).get().join('');
$('.out').val( allvals );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="in" type="text" id="i1"/>
<input class="in" type="text" id="i2"/>
<input class="in" type="text" id="i3"/>
<input class="out" type="text" id="i4"/>
I have a list of checkboxes like this:
<input type='checkbox' name='cat' class='parent' value='cat1' />Category 1</input>
<input type='checkbox' name='foo' class='child' value='1' />SubCategory 1</input>
<input type='checkbox' name='foo' class='child' value='1' />SubCategory 2</input>
<input type='checkbox' name='cat' class='parent' value='cat2' />Category 2</input>
<input type='checkbox' name='foo' class='child' value='3' />SubCategory 3</input>
<input type='checkbox' name='foo' class='child' value='4' />SubCategory 4</input>
I would like to change the 'Category 1' checkbox to checked whenever I click it's subcategories without checking the other categories checkbox.
How can I do that?
Using the data attribute to set the cat. simply get this form the check event of the child elements:
<input type='checkbox' name='cat' class='parent' value='cat1' id="category1" />Category 1</input>
<input type='checkbox' name='foo' class='child' value='1' data-cat="1" />SubCategory 1</input>
<input type='checkbox' name='foo' class='child' value='2' data-cat="1" />SubCategory 2</input>
....
$('.child').change(function() {
var cat = $(this).data('cat');
$('#category' + cat).prop('checked', true);
});
I made a slight change to your markup and wrapped the sets in a div each.
Now my code will uncheck the parent too if all its child-cats are unchecked and when you check the parent, all child cats are checked/unchecked
Live Demo
$(function() {
$(".child").on("click",function() {
$parent = $(this).prevAll(".parent");
if ($(this).is(":checked")) $parent.prop("checked",true);
else {
var len = $(this).parent().find(".child:checked").length;
$parent.prop("checked",len>0);
}
});
$(".parent").on("click",function() {
$(this).parent().find(".child").prop("checked",this.checked);
});
});
You can id the subCategories as cat2_1, cat2_2 etc and then access the category element by means of the subcategory element by splitting the id by _ to obtain the category id.
Other answer
$(document).ready(function () {
$("INPUT").click(function () {
if ($(this).attr("class") == "parent") {
var v = this.value;
var check = this.checked;
var ok = false;
$("INPUT").each(function () {
if (v == this.value) {
ok = true;
} else {
if (this.name=="cat") ok = false;
else if (ok && this.name == "foo") {
this.checked=check;
}
}
});
}
});
});
I need to form a string with the all values input fields within a div layer - using jquery
<div id="selection">
<input class="field" id="1" type="hidden" value="A"/>
<input class="field" id="2" type="hidden" value="B"/>
<input class="field" id="3" type="hidden" value="C"/>
<input class="field" id="4" type="hidden" value="D"/>
</div>
<input type="button" id="button" value="generate"/>
in this form:
id[1]=val[A]&id[2]=val[b]...so on
jquery:
$(function() {
$('#button').click(function() {
//function goes here...
});
});
If you use name instead of (or in addition to) id:
<input class="field" name="1" type="hidden" value="A"/>
<input class="field" name="2" type="hidden" value="B"/>
<input class="field" name="3" type="hidden" value="C"/>
<input class="field" name="4" type="hidden" value="D"/>
you can use serialize:
$('#button').click(function() {
alert($('#selection input').serialize());
});
which gives you
1=A&2=B&3=C&4=D
If you really want to have the id[x] structure, you can give the elements the names id[1], id[2] etc.
Edit: Oh, somehow I overlooked that you want val[x] as well. This would not be possible with serialize, only if you really put val[x] as value in the fields. But why do you need such an obfuscated structure?
Btw. you are missing type="button" at your button.
<script>
$(function() {
$('#button').click(function() {
var str = new Array();
var count = 0;
$('.field').each(
function()
{
str[count] = 'id['+$(this).attr('id')+']=val['+$(this).val()+']';
count++;
}
);
alert(str.join('&'))
});
});
</script>
<div id="selection">
<input class="field" id="1" type="hidden" value="A"/>
<input class="field" id="2" type="hidden" value="B"/>
<input class="field" id="3" type="hidden" value="C"/>
<input class="field" id="4" type="hidden" value="D"/>
</div>
<input id="button" value="generate" type="button"/>
Another solution that gives the exact specified output and handles missing attributes gracefully:
See it in action at jsFiddle:
$(function() {
$('#button').click(function() {
var ResStr = $('#selection input.field');
ResStr = ResStr.map (function () {
var jThis = $(this);
var ID = jThis.attr ("id");
if (!ID) ID = "null";
var VAL = jThis.val ()
if (!VAL) VAL = "null";
return 'id[' + ID + ']=val[' + VAL + ']';
} ).get () .join ('&');
alert (ResStr);
} );
} );
this returns all the html combined of all the inputs inside the div
var h = '';
var c = 0;
$('#selection input.field').each(function(){
h += '&id['+(++c)+']=val['+$(this).val()+']';
});
h = h.slice(1);
alert(h);