Set Input array value using jquery - javascript

I am trying to implement html input array.
<input type="text" name="firstName[]" id="firstName[]">
And i need to set value of another form which looks something like
<form id="tempForm">
<input type="text" name="userName" id="userName">
<input type="text" name="userId" id="userId">
</form>
into the input array using jquery on form submit.
For that i tried following on form submit,
var currentIndex=$("input[name^=firstName]").length;
$("#firstName").eq(currentIndex).val($("#userName").val());
But it doesn't works,obviously.
Question:
How to set value of input array using jquery?

Use the jquery append function for add inputs with different attribute value :
Check it :
$(document).ready(function(){
var a = ["username","userid"];
var b = ["username","userid"];
for( var i = ; i <3 ; i++){
$('#tempForm').append('<input type="text" name="'+a[i]+'" id="'+b[i]+'" />);
}
});
Then continue your other work:
replace this code with your js code :
var currentIndex=$("input[name^=firstName]").length;
$("#firstName").eq(currentIndex).val($("#"+userName).val());

Related

How do i get submitted form (inputs like name="array[key]") type data as array/object in js to use in submit callback

I have form in which i am submitting multiple inputs containing name attributes as array like name="array[key]"
<form onsubmit="callback($(this));">
<input type="text" name="stock[quantity]">
<input type="text" name="stock[old]">
<input type="text" name="form[mrp]">
<input type="text" name="form[price]">
</form>
I have tried new formData($("form")[0]) and jQuery $("form").serializeArray() both returning name="array[key]" as string.
I want this data as multidimensional object like we got this in php when submit this form like.
<script>
function callback($form){
/*
here i want form data in js object like
{
stock : {quantity : ... , old : ....},
form : {mrp : ... , price : ....}
}
or something like this
*/
}
</script>
I am using JS, jQuery, and Vue.js in this project, actually i want to put this form data to indexedDB after successful save on server. i have different tables/objectStore for stock and form
Try this..
function callback($form) {
let result = {};
let formData = $form.serializeArray();
formData.forEach(obj => {
let inputValue = obj.name.split('[');
if (!result[inputValue[0]]) {
result[inputValue[0]] = {};
}
let innerText = inputValue[1].replace(']','');
result[inputValue[0]][innerText] = obj.value;
});
console.log(result);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit="callback($(this)); return false;">
<input type="text" name="stock[quantity]">
<input type="text" name="stock[old]">
<input type="text" name="form[mrp]">
<input type="text" name="form[price]">
<input type="submit" value="submit">
</form>

How to get hidden array value from output to PHP

I got an output array code,
<output class="gst" id="op" name="Gst[]">0.00</output>
i got an input hidden array code,
<input type="hidden" id="gst2" name="Gst2[]">
I got a function to show the amount of gst for each output
function myFunction() {
debugger
var ele = document.querySelectorAll('input.input');
let sum = 0;
ele.forEach(input => {
sum += input.value ? parseFloat(input.value) : 0;
$(input).parents("tr").find(".gst").text((input.value * 0.07).toFixed(2));
});
document.getElementById('result').textContent = sum.toFixed(2);
}
my problem is, how do i get the hidden array gst2 value in PHP?
You can't get de hidden field value in PHP without wrapping it in a form and do a POST / GET request. You could do something like this:
<form method="POST">
<input type="hidden" id="gst2" name="Gst2[]">
<input type="submit" value="Submit">
</form>
After you submit the form $_POST['Gst2'] will be set and you can use that variable. You could do the same with method="GET".
EDIT:
You can find multiple solutions in this post:
https://stackoverflow.com/a/50412517/2075596
Just use input tag using same id and name.

Selecting all textbox at once with javascript

In my work we have to fill a lot of textboxes to do some validations. After all, we need to erase all - one by one - to restart the process.
Has some way to erase all textbox content with javascript (the only one method we can use now)? A for loop maybe?
You should put all the input fields in a form and then reset the form by the .reset() method.
document.getElementById("reset").onclick= ()=>{
document.getElementById("form").reset()
}
<form id="form">
<input/>
<input/>
</form>
<button id="reset">Reset</button>
See an example on W3Schools or the docs on MDN
If you want to restore the fields to their initial value, reset the form as suggested by #dota2pro's answer.
OTOH, if you want to clear the elements regardless of their initial value, you can query the elements using a type (aka "tag") CSS selector via Document​.query​SelectorAll()
and iterate through the elements as below:
function go() {
let inputs = document.querySelectorAll('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].value = '';
}
}
<input type="text" value="a"><br>
<input type="text" value="b"><br>
<input type="text" value="c"><br>
<br>
<button onclick="go()">click to clear</button>
Note that:
document.querySelectorAll('input') fetches all <input>s regardless of their type attribute.
document.querySelectorAll('input[type="text"]') fetches all <input type="text">.
document.querySelectorAll('textarea') fetches all <textarea>.
If you want to combine, you can use the comma combinator:
document.querySelectorAll('input[type="text"],textarea')
You can get in different ways in javascript:
By ID : document.getElementById("id")
By class: document.getElementsByClassName("class")
By tag:
document.querySelectorAll("input")
or Jquery
By ID : $("#id")
By class: $(".class")
By tag: $("input")
Read documentation about that here
tru
[...document.querySelectorAll('input')].map(x=>x.value='')
var clean = () => [...document.querySelectorAll('input')].map(x=>x.value='');
<button onclick="clean()">Clear</button><br>
<input type="text" value="some"><br>
<input type="text" value="short"><br>
<input type="text" value="text"><br>
Bellow code will select all editable text-boxes
document.querySelectorAll('input[type="text"]:not(:disabled):not([readonly]))')
If you have JQuery available, you can do:
$('input[type="text"]').val('');
Or, if you prefer native:
for(var i = 0; i < document.getElementsByTagName('input').length; i++){
document.getElementsByTagName('input')[i].value = '';
}

Javascript set value for Form obeject Array

I am looking to add data to a form object which is an array.
This works fine:
<input type="text" name="object" value="">
<script>document.form.object.value = "value";</script>
But when the object is an array it's not working:
<input type="text" name="object[]" value="">
<script>document.form.object[0].value = "value";</script>
The value of the object is not changing.... Any idea?
I would like to loop the script so I need to create an array. Didn't find any solution...
Per example, I would utilize document.form.elements['object[]'].value = "value". Otherwise, if you intended on having multiple form elements with the same name (multiple inputs with object[], and iterate via the collection, can use the following:
var myForm = document.form;
var myControls = myForm.elements['object[]'];
for (var i = 0; i < myControls.length; i++) {
var aControl = myControls[i];
}
The example provided, in your code, the name provided is not perceived as an array.
The attribute value "object[]" is just a string to JavaScript -- it does not interpret that as an array. However, when brackets appear in a name, you cannot use it any more in the dot-notation, but must write:
document.form["object[]"].value = "value";
<form name="form">
<input type="text" name="object[]" value="">
</form>
If you have more than one element with name="object[]", then the above will only target the first one of these. To set the value of all those elements, you must loop. This you can (for instance) do with the elements property and Array.from to iterate over those elements:
Array.from(document.form.elements["object[]"], function(elem) {
elem.value = "value";
});
<form name="form">
<input type="text" name="object[]" value="">
<input type="text" name="object[]" value="">
</form>
For those using IE: replace Array.from with [].map.call

Jquery not returning the values in form INPUTs

I have a login form on a modal jquery dialog with the usual 2 text INPUTs. When I enter a login name and password then click the submit, the call back function is called.
The first thing the callback does is try to extract the values of the two INPUTs, but the values returned are empty strings (I have a breakpont here, and have even stepped through the jquery processing of the objects - they objects are correctly identified as the fields on the form, but value="" for both).
At this point I can still see the values in the form, and when the callback exits and the focus goes back to the form, the values are still in the INPUTS. I also tried .prop("value") rather than .val(), but the result was the same.
I just can't figure why I can't read the values - any help appreciated.
<form id="cp-loginform" action="/cypo/index.php" method="POST" >
<input type="hidden" name="Login" value="Login">
<input type="hidden" name="pp" value="0" />
<input type="text" id="cp-loginname" name = "loginname" placeholder = "Login ID" class="loginforminput cp-width-50" autofocus >
<input type="password" id="cp-password" name = "password" placeholder = "password" class="loginforminput cp-width-50"></p>
<input type="submit" id="cp-submit" name = "submit" onclick="ProcessLogin()" ></p>
</form>
function ProcessLogin() {
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
console.log(loginval.concat(" ",passwordval));
}
PROBLEM RESOLVED:
I felt that this was a scope issue. The form itself was obviously OK (if submitted from the dialog it worked) - it was just the attempt to check the INPUT values using jquery that wasn't working.
I found that my select had to start with the dialog element and include a descendent path to my INPUTs. It's as if the dialog puts a wrapper around the elements inside so they are no longer visible as owned by the document.
If I login with xxx and zzz and step therough the following code I see this:
var loginval = $("#cploginname").val(); << = ""
var passwordval = $("#cppassword").val(); << = ""
var loginval = $("#cp-loginform #cploginname").val(); << = ""
var passwordval = $("#cp-loginform #cppassword").val(); << = ""
var loginval = $("#cpdialog #cp-loginform #cploginname").val(); << = "xxx"
var passwordval = $("#cpdialog #cp-loginform #cppassword").val(); << = "zzz"
console.log(loginval.concat(" ",passwordval));
I can't say I understand what's going on, but I have a solution so I am happy. Thanks to all who answered.
FINAL WORD
Thanks to #CMedina, I now understand. The form was defined in a hidden DIV at the top of my BODY section, and I passed $("#loginform") to a f() that created the dialog. The dialog was added to the DOM just before the . I had missed the fact that my original form was still in the DOM, so I was referencing that, not the dialog copy. When I included the dialog wrapper in the path, I finally 'found' the second copy.
Your button is the type submit (their natural behavior is to send the form). Remove the onclick in your button html.
<input type="submit" id="cp-submit" name = "submit">
You must add preventDefault to prevent submit the form and do what you want. Add the code JS for the button onclick event
$("#cp-submit").on("click", function(e){
e.preventDefault();
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
console.log(loginval.concat(" ",passwordval));
});
Result: https://jsfiddle.net/cmedina/svjqb2a4/
Try it :
<html>
<head>
</head>
<body>
<form id="cp-loginform" action="/cypo/index.php" method="POST">
<input type="hidden" name="Login" value="Login">
<input type="hidden" name="pp" value="0" />
<input type="text" id="cp-loginname" name = "loginname" placeholder = "Login ID" class="loginforminput cp-width-50" autofocus >
<input type="password" id="cp-password" name = "password" placeholder = "password" class="loginforminput cp-width-50">
<input type="submit" id="cp-submit" name ="submit" onclick="ProcessLogin(event)">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function ProcessLogin(e) {
e.preventDefault();
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
alert(loginval.concat(" ",passwordval));
}
</script>
</body>
</html>

Categories