put html input values into javascript object - javascript

Why isn't this code giving me an object with the keys as the ids of the text inputs, and the values as the values of the text inputs?
JS
$(document).ready(function () {
$('body').on('click', '#btn', function () {
var address = {};
$('input[type="text"].address').each(function (index, element) {
address[element.id] = $(element).val();
});
console.log(address);
});
});
HTML
<input class="address" id="attn" value="john doe">
<input class="address" id="address_1" value="1234 sample st">
<input class="address" id="address_2" value="Suite 1">
<input class="address" id="city" value="chicago">
<input class="address" id="state" value="IL">
<input class="address" id="zip" value="12345">
<input class="address" id="country" value="US">
<input type="button" id="btn" value="btn" />
jsbin

It's because your inputs don't have type="text" thus $('input[type="text"].address') is not returning anything.
It's better to add them to signify that the inputs are of type text.

Your inputs do not have the [type=text] attribute, so your selector matches none of them. Simply remove it, or use the :text selector:
var address = {};
$(':text.address').each(function (index, element) {
address[element.id] = element.value;
});
console.log(address);
(updated demo)

The jQuery attribute selector (as well as browser query selectors) work with the DOM elements rather than their properties. If you do not explicitly have the type attribute declaration on your the input elements, $("[type]") and document.querySelector("[type]") will not find the element even if its type property is text (http://jsfiddle.net/g76UC/).
The simplest solution is to add type=text to the input elements in your HTML. Another is to use a different selector that does not require this attribute definition. The final (and least desirable) would be to create a separate selector such as :prop that checks the element's type property instead. However this already exists in the form of jQuery's :text.

Use this
$('input.address').each(function () {
address[this.id]= $(this).val();
});
Demo http://jsbin.com/osufok/12/edit

Try out this one http://jsfiddle.net/adiioo7/TPYtg/
$(document).ready(function () {
$('#btn').on('click', function () {
var address = {};
$('.address').each(function (index, element) {
address[element.id] = $(element).val();
});
console.log(address);
});
});

Related

How to get a property of a changed input?

I have several inputs on which I want to handle the change event using .on("change"). I've put the inputs in an array of variables like that:
$(document).on("change keyup", [
input1,
input2,
input3
], function() {
// doing stuff
});
Each variable has a jQuery selector assigned to it like this:
var input1 = $("input[name=input1]");
var input2 = $("input[name=input2]");
var input3 = $("input[name=input3]");
Each input has a data attribute which I want to get from this context when the input is changed. For example if input1 has been changed, I want to get its data attribute the following way:
this.data("someAttribute")
But I'm afraid that this doesn't work with selectors from .on() function but with the initial $(document) selector and I'm actually trying to get the data attribute from document instead of the input that has been changed which is not what I need.
Note: With what I'm trying to do, selecting multiple inputs like this $(input1, input2, input3) doesn't work in my case.
Rather than group the inputs that need binding into an array and passing the array to the .on() method (which isn't allowed anyway), you should give the input elements in question a common CSS class and then write your event binding like this:
$(document).on("change keyup", ".theClass", function() {
// doing stuff
});
Then, within the event handler, you'll need to pass this to the JQuery function like this: $(this).data() because .data() is a JQuery method and won't be available on the native DOM element that this alone refers to.
Here's an example:
$(document).on("change keyup", ".input", function() {
console.log($(this).data("test"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' name='input1' class="input" data-test='one'>
<input type='text' name='input2' class="input" data-test='two'>
<input type='text' name='input3' class="input" data-test='three'>
Give all your inputs a CSS class
$('.change').on('change keyup', function() {
console.log($(this).val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="change">
<input type="text" class="change">
<input type="text" class="change">

Keyup function into form element

I have a script I am using to copy a field into another input field using keyup blur paste. This script works, however I need to modify it to also go into two different form elements which are named data-cost="" and debt="", instead of the <div id="viewer">
This is the script as I have it now :
$(function () {
$('#account_balance1').on('keyup blur paste', function() {
var self = this;
setTimeout(function() {
var str = $(self).val();
$("#viewer").text(str.replace(/^\$/, ''));
}, 0);
});
$("#viewer").text($('#Website').val().replace(/^\$/, ''));
});
This is the html :
<!--This where I get the value from -->
<input type="text" class="balance" id="account_balance1" name="cardb" value=""/>
<!--the first 2 elements are where I need the values to go -->
<input data-cost="" debt="" value="" type="checkbox" name="f_2[]"/>
if you need the two attributes (data-cost and debt) to be each set to your value you need:
$("input[data-cost][debt]").attr('data-cost',str.replace(/^\$/, ''));
$("input[data-cost][debt]").attr('debt',str.replace(/^\$/, ''));
Just use that selector then
$("input[data-cost][data-debt]")
I think you're maybe having a fundamental misunderstanding of what the data attributes are for? You're aware that they will not be posted with the form? I think what you're looking for is the data function which will allow you to set the data attributes http://api.jquery.com/data/.
Perhaps you want data-cost and data-debt?
So if your input looks like this:
<input data-cost="" data-debt="" value="" type="checkbox" name="f_2[]" id="checkboxId" />
Then you can set the values in your javascript like this:
var value1="some value";
var value2="another value";
$('#checkboxId').data('cost', value1);
$('#checkboxId').data('debt', value2);
I don't believe having an attribute named simply "debt" as you have it above is valid.
I'd do it this way (setTimeout was useless) :
$(function () {
$('#account_balance1').on('keyup blur paste', function () {
var self = this;
var nextCheckbox = $(self).next("input[type='checkbox']");
var str = $(self).val();
$("#viewer").text(str.replace(/^\$/, ''));
nextCheckbox.data({
cost: str,
debt: str
});
/*
You won't be able to see changes if you inspect element,
so just check in console
*/
console.log(nextCheckbox.data());
});
});
And your html markup must be slightly modified :
<!--This where I get the value from -->
<input type="text" class="balance" id="account_balance1" name="cardb" value="" />
<!--the first 2 elements are where I need the values to go -->
<input data-cost="" data-debt="" value="" type="checkbox" name="f_2[]" />
<!--I added the viewer to check if everything works properly -->
<div id="viewer"></div>

Set the default value of an input text

my requirement is to save the entire "html" inside a div, but when i load an "html" with text fields to a div and then editing the value of the text box, the newly set value doesn't reflect in the core "html". I tried to inspect the value with fire bug and it remains the same or no value at all.With "jquery" i tried to set attribute but no attribute name value is created. how can i set the value of text fields and then get that "html" with the newly set value.
here is my html
<div class="sub_input_box">
<input type="text" / class="boreder_line">
<input type="text" id="txt" value=""/>
<input type="hidden" id="hid" />
<div class="clear"></div>
</div>
and the jquery i used to set attribute
$("#txt").attr("value", "some value");
Chances are you're calling your jQuery code before the HTML input part. You can either place the jQuery stuff below it, or if you don't want to, you can do something like this:
$(document).ready(function(){
$("#txt").attr("value", "some value");
});
That will only run when the page is fully loaded.
However, it's unclear if you're using AJAX to load those inputs into your DOM. If so, you need to call $("#txt").attr("value", "some value"); in the onSuccess callback function which is fired after the AJAX successfully responds.
You can try something like this:-
<input name="example" type="text" id="example"
size="50" value="MyDefaultText" onfocus="if(this.value=='MyDefaultText')this.value=''"
onblur="if(this.value=='')this.value='MyDefaultText'" />
Have you tried:
$("#txt").val("Hello World!");
For setting the text value, and,
var my_string = $("#txt").val();
For getting the text value.
Let me know if it works.
Excellent question. You would think clone would do this on its own, alas, it doesn't.
Here is a sample than you can hopefully adapt to do what you need
HTML
<div id=divToCopy>
<input name=i1 value=foo><br>
<input name=i2 value=bar>
</div>
<input type=button onclick=copyDiv(); value='Copy the div'>
<div id=newDiv>
the copy will go here
</div>
JavaScript
function copyDiv() {
$('#newDiv').html($('#divToCopy').clone());
$('#divToCopy :input').each(function() {
var child=0;
for (var i = 0; i < this.attributes.length; i++) {
var attrib = this.attributes[i];
var prop=$(this).prop(attrib.name);
$($('#newDiv').find(' :input')[child]).prop(attrib.name,prop);
child++;
}
});
}
But it does work: http://jsbin.com/eXEROtU/1/edit
var html = '<input type="text" id="txt" value=""/>';
$(document).ready(function() {
$("#load").click(function() {
$("#sub_input_box").html(html);
});
$("#inspect").click(function() {
alert($("#txt").val());
});
});
$(document).on('focusout','input[type="text"]',function(a){
console.log(a.target.value);
a.target.setAttribute("value",a.target.value);
});
this is the solution i found, i had to set the value attribute explicitly on loose focus from the text field

How to make simplier the jquery code

Aim is to detect if after page load input values are changed.
Input fields (19 fields) for example
<input type="text" name="date_day1" id="date_day1" value=" >
<input type="text" name="date_month1" id="date_month1" value=" >
<input type="text" name="date_year1" id="date_year1" value=" >
<input type="text" name="amount1" id="amount1" value=" >
Then hidden input field like this
<input type="text" name="is_row_changed1" id="is_row_changed1" value="">
<script>
$("#date_day1").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
$("#date_month1").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
</script>
If in any of input fields (19 fields) value is changed, then I need to reflect it in this hidden input field (I decided to set the hidden input field value to 1).
After that ajax with php where I check if the hidden input field value is 1. If 1, then update mysql. Aim is to reduce usage of server resources.
Question
Javascript code for the hidden input field would be long. May be some way (code) to make is shorter (simplier)?
Add a row_changed class to each input then you can target them all with one call:
$(".row_changed").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
(you can also simplify it even more with QuickSilver's comment.)
You could use JQuery selectors in order to set the same "input changed" callback for all input elements declared in your HTML code:
var anyFieldChanged = false; //Global variable
function changedCallBack()
{
anyFieldChanged = true;
alert('Fields changed');
}
allInputs = $('input');
allInputs.each(function() { this.onchange = yourCallBack(); });
I don't know if it's just in your example code, but you have several elements with the same ID, which is not valid. Each ID should be unique (which is the purpose of any ID). You can either add a class to each input you want to track and select on that like Shawn said or if you want to track every input except the hidden on the page you can use
$("input:[type!=hidden]").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
Use like this.
<script>
$("#date_day1").on("change", function () {
$('#is_row_changed1').val(1);
});
$("#date_month1").on("change", function () {
$('#is_row_changed1').val(1);
});
// etc
</script>

Getting All Data-Bind Values Using JQuery

function getDbValue()
{
alert($('[data-bind]').length);
alert($('[data-bind][0].data-bind'));
alert($('[data-bind][0].value'));
jQuery.each($('[data-bind]'), function(databind,key)
{
alert(key);
alert(databind);
alert(databind[key].data-bind);
})
}
The above is my function and i want to read all inputs that have the properties data-bind within them for example
<input type="text" id="frmIn1-Officer" data-bind="value: AOfficer" class="InputText"/>
^ When running my function i would want it to return 'AOfficer' as that is the data-bind value.
So an example is
<input type="text" id="frmIn1-Officer" data-bind="value: AOfficer1" class="InputText"/>
<input type="text" id="frmIn1-Officer" data-bind="value: AOfficer2" class="InputText"/>
<input type="text" id="frmIn1-Officer" data-bind="value: AOfficer3" class="InputText"/>
<input type="text" id="frmIn1-Officer" data-bind="value: AOfficer4" class="InputText"/>
<input type="text" id="frmIn1-Officer" data-bind="value: AOfficer5" class="InputText"/>
<input type="text" id="frmIn1-Officer" data-bind="value: AOfficer6" class="InputText"/>
And in the for each loop i would like to be able to use the value of data bind..
e.g values[0] = 'AOfficer1'
Sorry if my explanation is slightly confusing, i have the idea in my head perfect but trying to put it in writing is alot harder.
jQuery interprets the "data-something" attributes differently than other attributes. So you should select all your elements and look for their data bindings like this:
$(document).ready(function(){
$('input.InputText').each(function(){
var input = $(this);
if ($(input).data().bind) {
alert($(input).data().bind);
}
});
});​
Then you can do string manipulation to parse out your values, I'd suggest using JSON and just loading it in like an object. Here's a working fiddle: http://jsfiddle.net/3NERK/6/
You can search for any element that has a data-bind attribute by the jQuery attribute selector - $("[data-bind]"), and then iterate on it with .each() and construct the dataBinds array out of it, stripping the value: out of each value.
This will do the trick:
dataBinds = [];
$("[data-bind]").each(function(){
dataBinds.push($(this).attr("data-bind").substring(7));
});​​​​​​
I've set up an example of it: http://jsfiddle.net/dvirazulay/YPnwQ/
$( "[data-bind]" ).each( function() {
var elem = $( this );
alert( elem.data( "bind" ) );
});
http://jsfiddle.net/NhNhK/
Get all elements with data-bind attribute: $('[data-bind]')
Iterating these elements and manipulating the data-bind attribute:
$('[data-bind]').each(function(element,index){
var data_bind = $(element).data('bind');
alert(data_bind);
})
You can use the .data() method with .each() to accomplish this.
DEMO
$('input').each(function() {
var $this = $(this);
alert($this.data('bind').replace("value: ", ""));
});​

Categories

Resources