Can not get the expected json out put from input values - javascript

I am trying but can not succeed to get my expected json output, Here is my code:
my html
<div class="form-field">
<input type='text' class='name' value="" >
<input name="" id="title" type="text" value="" size="40" aria-
required="true" class='value'><input type="button" value="convert"
id="convert"/><br>
<input type='text' class='name' value="">
<input name="" id="title" type="text" value="" size="40" aria-
required="true" class='value'>
</div>
my js:
var $index=1;
function convert(){
var $namevalue=[];
$('.name').each(function () {
$namevalue.push($(this).val());
});
// $namevalue= $('.name').val();
for(var i=0; i<$namevalue.length; i++){
//
$('.value').attr("name",$namevalue[i]);
}
}
// var $index=1;
$('#convert').click(function(){
$index++;
convert();
});
output of above code:
{"height":["blue","24"]}
HTML view:
But my expected output is like this:
{"color":"blue","height":27}
How can i achieve this, please help.

declare $namvevalue as an object var $namevalue={}. Then for each .name use its value as a key and next input val as value.
Also note your html as multiple elements with same id, you should not do that. use different id for each element.
var $index=1;
function convert(){
var $namevalue={};
$('.name').each(function () {
$namevalue[$(this).val()] = $(this).next('input').val();
});
// $namevalue= $('.name').val();
for(var i=0; i<$namevalue.length; i++){
//
$('.value').attr("name",$namevalue[i]);
}
console.log($namevalue);
}
// var $index=1;
$('#convert').click(function(){
$index++;
convert();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-field">
<input type='text' class='name' value="" >
<input name="" id="title1" type="text" value="" size="40" aria-
required="true" class='value'><input type="button" value="convert"
id="convert"/><br>
<input type='text' class='name' value="">
<input name="" id="title2" type="text" value="" size="40" aria-
required="true" class='value'>
</div>

You can use the index parameter of .each to access the .value field with the same index. You'll also have to change namevalue to an object instead of an array as you expect an object as the output.
e.g.
function convert() {
var namevalue = {};
var $vals = $('.value');
$('.name').each(function(index) {
namevalue[$(this).val()] = $vals.eq(index).val();
});
return namevalue;
}
$('#convert').click(function() {
var namevals = convert();
console.log(namevals);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-field">
<input type='text' class='name' value="">
<input name="" id="title" type="text" value="" size="40" aria- required="true" class='value'>
<input type="button" value="convert" id="convert" /><br>
<input type='text' class='name' value="">
<input name="" id="title" type="text" value="" size="40" aria- required="true" class='value'>
</div>

Related

Adding two input boxes values with multiple input fields not working in jQuery

I have website in which I have a form, where there is a input fields like below. As you can see I'm trying to add two input boxes to get the values of the third, however this is working only with first set of input box, for the rest its coming faulty or the values of first set. How can I fix this?
$(document).ready(function() {
$(".value2").keyup(function() {
var val1 = +$(".value1").val();
var val2 = +$(".value2").val();
$(".result").val(val1 * val2);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input name="quantity[]" type="text" class="form-control value1">
<input name="rate[]" type="text" class="form-control value2">
<input name="amount[]" type="text" class="form-control result">
<input name="quantity[]" type="text" class="form-control value1">
<input name="rate[]" type="text" class="form-control value2">
<input name="amount[]" type="text" class="form-control result">
<input name="quantity[]" type="text" class="form-control value1">
<input name="rate[]" type="text" class="form-control value2">
<input name="amount[]" type="text" class="form-control result">
Wrap in containers and delegate from the parent div of the element you update
The data here is relative to the field you update
NOTE: Add a main container with an ID and wrap each set in divs too
$(document).ready(function() {
$("#container").on("input",".form-control", function() {
const $parent = $(this).closest("div.item")
var val1 = +$(".value1", $parent).val();
var val2 = +$(".value2", $parent).val();
$(".result", $parent).val(val1 * val2);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="container">
<div class="item">
<input name="quantity[]" type="text" class="form-control value1">
<input name="rate[]" type="text" class="form-control value2">
<input name="amount[]" type="text" class="form-control result">
</div>
<div class="item">
<input name="quantity[]" type="text" class="form-control value1">
<input name="rate[]" type="text" class="form-control value2">
<input name="amount[]" type="text" class="form-control result">
</div>
<div class="item">
<input name="quantity[]" type="text" class="form-control value1">
<input name="rate[]" type="text" class="form-control value2">
<input name="amount[]" type="text" class="form-control result">
</div>
</div>
The issue is because when you call val(), amongst other jQuery methods, on a jQuery object holding a collection of elements, it only evaluates against the first element in that collection.
To fix your issue you can use jQuery's DOM traversal methods to retrieve the related elements in the DOM to the one which raised the event. In this case, prev() and next():
jQuery($ => {
$(".value2").on('input', e => {
let $val2 = $(e.target);
let val1 = +$val2.prev(".value1").val() || 0;
let val2 = +$val2.val() || 0;
$val2.next(".result").val(val1 * val2);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input name="quantity[]" type="text" class="form-control value1">
<input name="rate[]" type="text" class="form-control value2">
<input name="amount[]" type="text" class="form-control result">
<input name="quantity[]" type="text" class="form-control value1">
<input name="rate[]" type="text" class="form-control value2">
<input name="amount[]" type="text" class="form-control result">
<input name="quantity[]" type="text" class="form-control value1">
<input name="rate[]" type="text" class="form-control value2">
<input name="amount[]" type="text" class="form-control result">
Note in the above example the use of input over keypress so that the logic also works when the user adds content to the input using the mouse. Also note the use of || 0 to coerce a NaN value to a 0.

Javascript loop through multiple forms, get all input values

I need to build an object from multiple forms input values without using jQuery.
<div id="formMain">
<form id="form_id_1" class="formClass">
<div id="fullname">
<p>Full Name</p>
<input type="text" class="inputClass" name="name" value="Joe">
<br/>
<input type="text" class="inputClass" name="name2" value="Doe">
</div>
<div id="Address">
<p>Address</p>
<input type="text" class="inputClass" name="address" value="1st Maint Street">
</div>
</form>
<form id="form_id_2" class="formClass">
<div id="fullname">
<p>Full Name</p>
<input type="text" class="inputClass" name="name" id="name1" value="Mary">
<br/>
<input type="text" class="inputClass" name="name2" id="name2" value="Doe">
</div>
<div id="Address">
<p>Address</p>
<input type="text" class="inputClass" name="address" id="addressId" value="2nd Maint Street">
</div>
</form>
</div>
final result should be object:
"profile":[
{
"name":"Joe",
"name2":"Doe",
"address":"1st Maint Street",
},
{
"name":"Mary",
"name2":"Doe",
"address":"2nd Maint Street",
},
The forms can be added dynamically by user, so I can have multiple forms embedded in the main form div.
I´m able to get the the first form values, but I´m getting stuck when multiple forms are added, I trying to loop throough the main element but just not working. The above is my 1st code sample working.
var formdata = document.getElementById('formMain').getElementsByTagName('input')
var form = [].map.call(formdata, function( input ) {
return {'value':input.value};
});
Have a look at this - using querySelectorAll, forEach and push.
Alternatively Array.map as long as the callback returns the objects created.
the HTML element collection needs to be cast to an Array to use map
console.log("Using forEach on the HTML collection")
let profile = [];
document.querySelectorAll("form").forEach(f => {
let obj = {};
f.querySelectorAll("input").forEach(ele => obj[ele.name] = ele.value || "");
profile.push(obj)
})
console.log(profile)
// ---------------------------------------------------------------
console.log("Using Array.map on a HTML collection cast to Array")
profile = [...document.querySelectorAll("form")].map(f => {
let obj = {};
f.querySelectorAll("input").forEach(ele => obj[ele.name] = ele.value || "");
return obj;
})
console.log(profile)
<div id="formMain">
<form id="form_id_1" class="formClass">
<div id="fullname">
<p>Full Name</p>
<input type="text" class="inputClass" name="name" value="Joe">
<br/>
<input type="text" class="inputClass" name="name2" value="Doe">
</div>
<div id="Address">
<p>Address</p>
<input type="text" class="inputClass" name="address" value="1st Maint Street">
</div>
</form>
<form id="form_id_2" class="formClass">
<div id="fullname">
<p>Full Name</p>
<input type="text" class="inputClass" name="name" id="name1" value="Mary">
<br/>
<input type="text" class="inputClass" name="name2" id="name2" value="Doe">
</div>
<div id="Address">
<p>Address</p>
<input type="text" class="inputClass" name="address" id="addressId" value="2nd Maint Street">
</div>
</form>
</div>
var forms = document.querySelectorAll("form");
var result = Array.from(forms).map(a => {
var obj = {};
Array.from(a.querySelectorAll("[name]")).forEach(b => {
obj[b.getAttribute("name")] = b.value;
});
return obj;
});
console.log(result);
<div id="formMain">
<form id="form_id_1" class="formClass">
<div id="fullname">
<p>Full Name</p>
<input type="text" class="inputClass" name="name" value="Joe">
<br/>
<input type="text" class="inputClass" name="name2" value="Doe">
</div>
<div id="Address">
<p>Address</p>
<input type="text" class="inputClass" name="address" value="1st Maint Street">
</div>
</form>
<form id="form_id_2" class="formClass">
<div id="fullname">
<p>Full Name</p>
<input type="text" class="inputClass" name="name" id="name1" value="Mary">
<br/>
<input type="text" class="inputClass" name="name2" id="name2" value="Doe">
</div>
<div id="Address">
<p>Address</p>
<input type="text" class="inputClass" name="address" id="addressId" value="2nd Maint Street">
</div>
</form>
</div>
querySelectorAll (mdn) can be used to fetch the forms and inputs.
flatMap (mdn) can be used to map forms to inputs.
spread syntax [...iterable] (mdn) can be used to convert the node list returned by querySelectorAll to an array.
let inputs = [...document.querySelectorAll('form')].flatMap(a => [...a.querySelectorAll('input')]);
console.log(inputs);
<div id="formMain">
<form id="form_id_1" class="formClass">
<div id="fullname">
<p>Full Name</p>
<input type="text" class="inputClass" name="name" value="Joe">
<br/>
<input type="text" class="inputClass" name="name2" value="Doe">
</div>
<div id="Address">
<p>Address</p>
<input type="text" class="inputClass" name="address" value="1st Maint Street">
</div>
</form>
<form id="form_id_2" class="formClass">
<div id="fullname">
<p>Full Name</p>
<input type="text" class="inputClass" name="name" id="name1" value="Mary">
<br/>
<input type="text" class="inputClass" name="name2" id="name2" value="Doe">
</div>
<div id="Address">
<p>Address</p>
<input type="text" class="inputClass" name="address" id="addressId" value="2nd Maint Street">
</div>
</form>
</div>
you can try like below
var formMain = document.getElementById("formMain");
var formMresultAreaain = document.getElementById("resultArea");
var result = [];
var formData = '<form class="formClass">' +
'<div id="fullname">' +
'<p>Full Name</p>' +
'<input type="text" class="inputClass" name="name" value="Joe">' +
'<br/>' +
'<input type="text" class="inputClass" name="name2" value="Doe">' +
'</div>' +
'<div id="Address">' +
'<p>Address</p>' +
'<input type="text" class="inputClass" name="address" value="1st Maint Street">' +
'</div>' +
'</form>';
function addForm() {
formMain.innerHTML += formData;
}
function submitForms() {
var forms = document.getElementsByTagName("form");
var inputs;
var tempResult = {};
result = [];
for (var i = 0; i < forms.length; i++) {
inputs = forms[i].getElementsByTagName("input");
tempResult = {};
for (var j = 0; j < inputs.length; j++)
tempResult[inputs[j].name] = inputs[j].value;
result.push(tempResult);
}
console.log(result);
}
<input type="button" onclick="addForm()" value="Add Form" />
<div id="formMain">
</div>
<hr/>
<input type="button" onclick="submitForms()" value="Submit" />

How to get data-attribute value of elements which is greater than given value using jquery?

I have few textboxes and data-attrribute for installment number.
<input type="text" id="54" data-instno="12"/>
<input type="text" id="124" data-instno="13"/>
<input type="text" id="88" data-instno="14"/>
<input type="text" id="126" data-instno="15"/>
<input type="text" id="102" data-instno="16"/>
<input type="text" id="8" data-instno="17"/>
<input type="text" id="87" data-instno="18"/>
<input type="text" id="112" data-instno="19"/>
If my installment number is 15. i want to get controls have data-instno>=15. that means last 5 textboxes in this case.
Use jQuery Has Attribute Selector [name] to selecting target elements and use .filter() to filtering element has data-instno great than 15.
$("[data-instno]").filter(function(){
return $(this).attr("data-instno") >= 15;
}).doSomething();
$("[data-instno]").filter(function(){
return $(this).attr("data-instno") >= 15;
}).css("background", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="54" data-instno="12"/>
<input type="text" id="124" data-instno="13"/>
<input type="text" id="88" data-instno="14"/>
<input type="text" id="126" data-instno="15"/>
<input type="text" id="102" data-instno="16"/>
<input type="text" id="8" data-instno="17"/>
<input type="text" id="87" data-instno="18"/>
<input type="text" id="112" data-instno="19"/>
If you want to get value of data-instno use this
var arr = $("[data-instno]").map(function(){
return $(this).attr("data-instno");
}).get().filter(function(value){
return value >= 15;
});
var arr = $("[data-instno]").map(function(){
return $(this).attr("data-instno");
}).get().filter(function(value){
return value >= 15;
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="54" data-instno="12"/>
<input type="text" id="124" data-instno="13"/>
<input type="text" id="88" data-instno="14"/>
<input type="text" id="126" data-instno="15"/>
<input type="text" id="102" data-instno="16"/>
<input type="text" id="8" data-instno="17"/>
<input type="text" id="87" data-instno="18"/>
<input type="text" id="112" data-instno="19"/>
Just plain JavaScript:
console.log(
[].filter.call(document.getElementsByTagName('INPUT'),
function(elem) {
return elem.dataset.instno >= 15;
})
);
<input type="text" id="54" data-instno="12"/>
<input type="text" id="124" data-instno="13"/>
<input type="text" id="88" data-instno="14"/>
<input type="text" id="126" data-instno="15"/>
<input type="text" id="102" data-instno="16"/>
<input type="text" id="8" data-instno="17"/>
<input type="text" id="87" data-instno="18"/>
<input type="text" id="112" data-instno="19"/>
var arrNumber = new Array();
$('input[type=text]').each(function(){
if($(this).attr('data-instno') >= 15){
arrNumber.push($(this).attr('data-instno'));
}
});
use this you will get this as an array

Trying to validate my form with error messages, doesn't seem to work

I want to pass in different element IDs with the same function
function validate(idname, spnname) {
var getId = document.getElementById(idname);
if(getId === null || getId === undefined || getId === "") {
var getSpn = document.getElementById(spnname).innerHTML = "Required Field";
}
}
validate('firstname', 'spnfirstname');
<body>
<h1>SUBSCRIBE</h1>
<form id="frml" method="get" >
<input type="text" name="fname" placeholder="First Name" class="textbox" id="firstname"/><span id="spnfirstname"></span><br />
<input type="text" name="lname" placeholder="Last Name" s="textbox" id="lastname"/><span id="spnlastname"></span><br />
<input type="date" name="Birthday" value="" class="textbox" id="birthday"/>
<span id="spnbirthday"></span><br />
<input type="email" name="" placeholder="someone#example.com" class="textbox" id="email"/><span id="spnemail"></span><br />
<input type="tel" name="" placeholder="Home Phone" class="textbox" id="homep"/><span id="spnhomep"></span><br />
<input type="tel" name="" placeholder="Cell Phone" class="textbox" id="cellp"/><span id="spncellp"></span><br />
//is there another way to do this onClick event in javascript that may help?
<input id ="btn" type="button" value="Submit" onClick = "return validate()"/>
</form>
</div>
I am receiving an error for my second var and my html onClick. My question is different because there is no answer here responding to this issue correctly. I have tried everything. I have no idea why I am getting this error message.
Two things:
1.- Use the 'value' property to get the actual value from the input:
var getId = document.getElementById(idname).value;
2.-Set the function to the 'click' event, addEventListener can be useful if you want to use plain javaScript, just right after the form:
<script>
document.getElementById('btn').addEventListener('click', function(){validate('firstname', 'spnfirstname');});
</script>
This is how i get it work.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function validate(idname, spnname){
var getId = document.getElementById(idname).value;
console.log(getId);
if(getId === null || getId === undefined || getId === ""){
var getSpn = document.getElementById(spnname).innerHTML = "Required Field";
}
}
</script>
</head>
<body>
<h1>SUBSCRIBE</h1>
<form id="frml" method="get">
<input type="text" name="fname" placeholder="First Name" class="textbox" id="firstname"/><span id="spnfirstname"></span><br/>
<input type="text" name="lname" placeholder="Last Name" class="textbox" id="lastname"/><span id="spnlastname"></span><br/>
<input type="date" name="Birthday" value="" class="textbox" id="birthday"/>
<span id="spnbirthday"></span><br/>
<input type="email" name="" placeholder="someone#example.com" class="textbox" id="email"/><span id="spnemail"></span><br/>
<input type="tel" name="" placeholder="Home Phone" class="textbox" id="homep"/><span id="spnhomep"></span><br/>
<input type="tel" name="" placeholder="Cell Phone" class="textbox" id="cellp"/><span id="spncellp"></span><br/>
//is there another way to do this onClick event in javascript that may help
<input id ="btn" type="button" value="Submit"/>
</form>
<script>
document.getElementById('btn').addEventListener('click', function(){validate('firstname', 'spnfirstname');});
</script>
</body
</html>
If you are trying to validate all your elements on submit click.
You can select all using querySelector and and then check each element for its value. If value is "" then change the innerHTML of sibling span element.
var submit = document.querySelector("#btn")
submit.addEventListener("click", function() {
var elements = document.querySelectorAll("input");
for (var i = 0; i < elements.length; i++) {
if (elements[i].value === "") {
elements[i].nextElementSibling.innerHTML = "Required Field";
}
}
});
<body>
<h1>SUBSCRIBE</h1>
<form id="frml" method="get">
<input type="text" name="fname" placeholder="First Name" class="textbox" id="firstname" /><span id="spnfirstname"></span>
<br />
<input type="text" name="lname" placeholder="Last Name" class="textbox" id="lastname" /><span id="spnlastname"></span>
<br />
<input type="date" name="Birthday" value="" class="textbox" id="birthday" />
<span id="spnbirthday"></span>
<br />
<input type="email" name="" placeholder="someone#example.com" class="textbox" id="email" /><span id="spnemail"></span>
<br />
<input type="tel" name="" placeholder="Home Phone" class="textbox" id="homep" /><span id="spnhomep"></span>
<br />
<input type="tel" name="" placeholder="Cell Phone" class="textbox" id="cellp" /><span id="spncellp"></span>
<br />
<input id="btn" type="button" value="Submit" />
</form>
</div>

number increment button

I have an existing html form which use array to store multiple row values. So I do not have a specific name for the same field for different row. In the PHP page i match the row according to the index.
In the form below, how do I make the button + and - to increase and decrease the value of the quantity of the specific row?
ROW 1
<input type="text" name="product[]" />
<input type="text" name="price[]" value="" onChange="updatePrice()" />
<input type="text" name="quantity[]" value="" onChange="updatePrice()" />
<input type="button" onclick="inc(this)" value="+"/>
<input type="button" onclick="dec(this)" value="-"/>`
ROW 2
<input type="text" name="product[]" />
<input type="text" name="price[]" value="" onChange="updatePrice()" />
<input type="text" name="quantity[]" value="" onChange="updatePrice()" />
<input type="button" onclick="inc(this)" value="+"/>
<input type="button" onclick="dec(this)" value="-"/>
ROW 3
<input type="text" name="product[]" />
<input type="text" name="price[]" value="" onChange="updatePrice()" />
<input type="text" name="quantity[]" value="" onChange="updatePrice()" />
<input type="button" onclick="inc(this)" value="+"/>
<input type="button" onclick="dec(this)" value="-"/>
In my opinion you first should to numerate items:
<input type="text" name="product[]" />
<input id="price-1" type="text" name="price[]" value="" onChange="updatePrice(1)" /> <!-- row number -->
<input id="qty-1" type="text" name="quantity[]" value="" onChange="updatePrice(1)" />
<input type="button" onclick="inc('qty-1')" value="+"/>
<input type="button" onclick="dec('qty-1')" value="-"/>
Then use javascript to manipulate items:
<script>
function inc(id) {
stepQty(id, +1);
}
function dec(id) {
stepQty(id, -1);
}
function stepQty(id, step) {
var value = $('#'+id).val();
$('#'+id).val(value + step);
}
function updatePrice(id) {
var a = $('#price-'+id).val() || 0;
var b = $('#qty-'+id).val() || 0;
$('#'+id).val(a*b);
}
</script>

Categories

Resources