Help me please:
I have a dynamic part of a module (generated by php application), for example:
<input type="text" class="attr" name="Input_0"/>
<input type="text" class="attr" name="Input_1"/>
...
<input type="text" class="attr" name="Input_n"/>
The value n is random (n> = 1). Obviously at the bottom of the form there's a submit button that confirms the completion of fields.
So, I need a procedure to read the modified values of the input tag via jquery script that gives this output:
Input_1 = value
Input_5 = value
...
Input_n = value
How can I do this?
here is some sample code :
var $inputs = $('#form_id :input');
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
});
Try serializing the form data and looping through the inputs and their values:
$('form').submit(function(e) { // when we submit the form
e.preventDefault();
// loop through form data and print values
var data = $.each($(this).serializeArray(), function(i, value) {
console.log(value);
});
});
Check out this fiddle: http://jsfiddle.net/kukiwon/ECz52/
Related
I'm using serializeArray() to retrive the form attributes. When I try to get the attributes, I'm receiving name and value for all the fields.
I have checked the documentation https://api.jquery.com/serializeArray/. I understood it will return the name and value of all the fields.
Now I have few custom attributes for some fields. I want to retrieve them using those custom attributes.
How can i achieve this?
Here is my logic.
var data = $('form').serializeArray();
var newData = {};
var queue = {};
data.forEach(function(field) {
if( field.customField != undefined && field.customField.indexOf("true")>=0 ) {
queue[field.name] = frm.value
} else {
newData[frm.name] = frm.value;
}
});
I need to get that customField attribute, I'm adding that to the HTML field attribute.
May not be the best, but you can do like this.
Let's say you have set of text boxes, text areas and so on with custom data attributes in it. What I am doing here is adding a class to those fields that you need to get value / data attributes in it.
Let's take the following HTML as an example.
HTML
<form id="frm">
<input class="serialize" type="text" name="title1" value="Test title 1" data-test1="test AAA" data-test2="test BBB" /><br/>
<input class="serialize" type="text" name="title2" value="Test title 2" data-test1="test CCC" data-test2="test DDD" /><br/>
<textarea class="serialize" data-test1="textarea test 1">TEST 22 TEST 11</textarea>
<button id="btn" type="button">Serialize</button>
</form>
What I am doing here is iterating through fields which has class .serialize and putting value, name, data attributes and so on to an array.
jQuery
$(document).ready(function(){
$('#btn').on('click', function(e) {
var dtarr = new Array();
$(".serialize").each(function(){
var sub = new Array();
sub['name'] = $(this).attr('name');
sub['value'] = $(this).val();
//data attribute example
sub['data-test1'] = $(this).data('test1');
sub['data-test2'] = $(this).data('test2');
dtarr.push(sub);
});
// This will give you the data array of input fields
console.log(dtarr);
});
});
Hope this helps.
I have some input in my form,now I want to get the json object from the form without some input named point,What's wrong with my code?I have to remove them.It seems not work for not() function.How to fix my code?
<form id="myform">
<input name='student' value='a'/>
<input name='student' value='b'/> '
...
<input name='point' value='90'/>
<input name='point' value='95'/>
</form>
Now I only want to submit the student data to the server.So I write the code:
var data = $('#myform').not("input[name='point']").serializeArray();
var objParam = {};
$.each(data, function(i, v) {
objParam[v.name] = v.value;
});
but the result still have point data.What's wrong with not() function?
breaking down your code $('#myform') selects your form, in this case, only one object, then you filter that object with .not("input[name='point']") but there is only one object which is the form itself.
You want to filter the form's children instead, so just add .children() like this:
var data = $('#myform').children().not("input[name='point']").serializeArray();
var objParam = {};
$.each(data, function(i, v) {
objParam[v.name] = v.value;
});
Hope this will help you.
$('#myform input[name!=point]').serializeArray()
Your selector is faulty.
$('#myform').not("input[name='point']").serializeArray()
...says, "Serialise the form with ID 'myForm' which is not also an input and has the name 'point'.
Rather, you mean: "Serialise the form with ID 'myForm' but omit its child inputs with name 'point'.
Here's a non-jQuery way, using native FormData.
//get the form as form data
var fd = new FormData(document.querySelector('#myform'));
//delete any elements pertaining to [name=point]
fd.delete('point');
//et voila; this shows we retain only the student fields
for (var key of fd.keys()) alert(key);
How can you make the browser remember what the user typed in the form, which has not yet been submitted and make the page refreshing not affect the data entered?
I have a form in which the user enters a number. Initially the form has 0 by default. I am storing the data in localStorage, so the browser can remember the data. However, when the page is refreshed, the user-entered data disappears and 0 is displayed by default. (still the localStorage data exists for it)
I tried to use jQuery's
$(".formClassName").val(localStorage.getItem(key));
but it does not work. Can anyone give me a piece of advice on this?Thank you in advance.
Edited: My form looks like this:
<form>
<!--There are multiple forms, and the only difference among them is the "name" attribute -->
Enter a number <input type="text" value="0" class"dataEntered" name="****">
<!--The button below saves the data entered in the above form -->
<input type="button" class="savedata" value="Save Value" name="****">
</form>
And I am adding the data to localStorage like below:
//JavaScript
<script>
//Using on because the website retrieves the above form dynamically
$(document).on("click", ".saveData", function(e){
//retrieve the number entered in the form
var userNum = $(this).siblings(".dataEntered").val();
//retrieve the value in name attribute
var thisFormName = $(this).attr("name");
//store the data
localStorage.setItem(thisFormName, userNum);
//Now that the save button has been pressed (not submitted to the
//server yet), and the data is stored in localStorage, I want to
//the page to show the number in userNum even after you refresh the page
//but this does not work.
$(".dataEntered").val(localStorage.setItem(thisFormName));
});
</script>
use cookie:
function addCookie(sName,sValue,day) {
var expireDate = new Date();
expireDate.setDate(expireDate.getDate()+day);
document.cookie = escape(sName) + '=' + escape(sValue) +';expires=' + expireDate.toGMTString();
}
function getCookies() {
var showAllCookie = '';
if(!document.cookie == ''){
var arrCookie = document.cookie.split('; ');
var arrLength = arrCookie.length;
var targetcookie ={};
for(var i=0; i<arrLength; i++) {
targetcookie[unescape(arrCookie[i].split('=')[0])]= unescape(arrCookie[i].split('=')[1]);
}
return targetcookie;
}
addCookie('type','1',1024);
var cookiesample = getCookies();
$(".formClassName").val(cookiesample.type);
cookiesample.type could be remembered unless the cookie is deleted.
Checkout this codepen I have it shows a functional solution to the problem. Also you need to make sure jQuery script checks if the DOM is ready, you can do that by using $(function() { }) a short hand for .ready().
$(function() {
var input = $("[type=text]");
var thisFormName = input.attr("name");
if (localStorage.getItem(thisFormName)) {
var value = parseInt(localStorage.getItem(thisFormName));
input.val(value);
}
$(document).on("click", ".savedata", function(e) {
var userNum = input.val();
localStorage.setItem(thisFormName, userNum);
input.val(localStorage.getItem(thisFormName));
});
});
I am new to KnockoutJS and I would like to serialize the current form, but when I console.log the serialized the form, it is empty.
How can I refer to the current form ?
Here is my DOM :
<form data-bind="submit: onSubmit">
<input type="text" data-bind="value: firstName">
<input type="text" data-bind="value: lastName">
<button data-bind="click: capitalizeLastName">Go caps</button>
<input type="submit" value="submit">
</form>
Here, the JS code :
$(document).ready(function () {
function AppViewModel() {
var self = this;
self.firstName = ko.observable("Bert");
self.lastName = ko.observable("Bertington");
self.fullName = ko.computed(function() {
return self.firstName() + " " + self.lastName();
}, self);
self.capitalizeLastName = function() {
var currentVal = self.lastName(); // Read the current value
self.lastName(currentVal.toUpperCase()); // Write back a modified value
};
self.onSubmit = function(form) {
// alert( self.firstName()) ;
console.log($(form).serialize()) ;
}
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
});
You are correctly referring to the current form in your code: it gets passed as the first argument to the submit data binding handler, however, only input with a name attribute are serialized by jQuery.serialize() method. Add name attributes to your fields and it will work.
From https://api.jquery.com/serialize/ (bold is mine)
Note: Only "successful controls" are serialized to the string. No
submit button value is serialized since the form was not submitted
using a button. For a form element's value to be included in the
serialized string, the element must have a name attribute. Values from
checkboxes and radio buttons (inputs of type "radio" or "checkbox")
are included only if they are checked. Data from file select elements
is not serialized.
However, I would advise you to follow #James Thorpe suggestion in the comments and get the form values from Knockout.js observables instead.
I know this is an extremely basic question but I'm stuck on this.
I have two input boxes and I want to calculate those inputs and show the result into another input (3rd one) immediately without the need of a submit button.
I means, once I start entering the values into the input and the result will shows live in the 3rd input which is the represent the result...
<input type="text" class="input value1">
<input type="text" class="input value2">
<input type="text" disabled="disabled" id="result">
<script>
$(document).ready(function(){
var val1 = $(".value1").val();
var val2 = $(".value2").val();
$(".input").keyup(function(){
$("#result").text(val1+val2);
});
});
</script>
Put val1 and val2 in keyup statement.
$(document).ready(function(){
$(".input").keyup(function(){
var val1 = +$(".value1").val();
var val2 = +$(".value2").val();
$("#result").val(val1+val2);
});
});
Look at fiddle: http://jsfiddle.net/g7zz6/
Under the assumption of SUM as you stated, the inputs will be numberic in nature.
$(".input").on("change", function(){
var ret = Number($(".value1").val()) + Number($(".value2").val());
$("#result").val(ret);
}
just set the text value, also you need to parse them as other wise they will be concatenated as strings.
$(document).ready(function () {
var val = parseInt($(".value1").val()) + parseInt($(".value2").val());
$("#result").text(val);
});
Live Demo
function addinput(){
var x= Number(document.getElementById("first").value);
var y= Number(document.getElementById("second").value);
var z= Number(x+y);
document.getElementById("l").value = Number(z);
}