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: ", ""));
});
Related
I want to get current class value <input type="text" id="contact_name1" name="name1"/> In js i want to call like this $('#contact_name1').on('input', function() { }.
my question is how to write after underscore current class.
$(#contact_"")? name1 changes for all classes.
You could use the starts with ^= operator inside the attribute selector:
$("[id^='contact_']").on("input", fn);
$("[id^='contact_']").on("input", function() {
var suffix = this.id.split("_")[1];
console.log( "ID: %s SUFFIX: %s", this.id, suffix );
});
<input id="contact_name" name="name" type="text">
<input id="contact_surname" name="surname" type="text">
<input id="contact_email" name="email" type="text">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I may suggest using starts with selector. and you can get your class name like this:
$('input[id^="contact_"]').on('input', function(e) {
var className = $(e.currentTarget).prop("class")
}
Hope it helps
i made this exemple few days ago
<script>
$("input").click(function(){
var res="#"+$(this).attr('id')
$(res).show()
});
</script>
just create a variable who contains the entire text and after this you can lauch your function :)
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">
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>
This is my form example:
<form action="" method="POST">
<input type="text" name="firstTarget" />
<input type="text" name="secondTarget" />
<input type="text" name="thirdTarget" />
<textarea name="result">I have this text and I want to update it using firstTarget. After that I want to use secondTarget and thirdTarget</textarea>
</form>
I want to update my textarea value in realtime by replacing the words firstTarget, secondTarget and thirdTarget with the actual values from firstTarget, secondTarget and thirdTarget inputs.
You can do something like this:
/* cache original value so we keep the keywords*/
var txt=$('textarea').val();
$('input').keyup(function(){
var newText=txt;
newText=newText.replace( this.name, this.value);
$('textarea').val(newText);
});
One issue however is if textarea is not set as readonly and user changes anything within it this won't work as it relies on storing the original value and changing that. Would need to know more about use case for this setup to help advance it further.
Same issue exists in other solutions as well if user touches any of the keywords all will fail
DEMO
Here's a solution that stores the input value on every keyup so textarea can be edited by user as well.
$('input').keyup(function(){
/* value to be replaced is stored in data object*/
var regVal=$(this).data('replace');
var newText=$('textarea').val().replace( regVal, this.value);
/* store value that will get replaced*/
$(this).data('replace', this.value)
$('textarea').val(newText);
}).each(function(){
/* on page load set initial replacement value as name of input*/
$(this).data('replace', this.name);
});
Only limitation is it assumes no duplicate entries by user
DEMO
HTML:
<form action="" method="POST">
<input type="text" name="firstTarget" onblur="tst(this);" />
<input type="text" name="secondTarget" onblur="tst(this);" />
<input type="text" name="thirdTarget" onblur="tst(this);" />
<textarea style="width:500px; height: 100px;" name="result">I have this text and I want to update it using firstTarget. After that I want to use secondTarget and thirdTarget</textarea>
</form>
And javascript:
function tst(elm){
var trgt=document.getElementsByTagName('textarea')[0];
trgt.value=trgt.value.replace(elm.getAttribute('name'), elm.value);
}
Working jsfiddle demo here
EDIT:
should you want to update multple instances of your needles like firstTarget, then you need to create the regex on the fly so you can pass it the global flag.
function tst(elm){
var trgt=document.getElementsByTagName('textarea')[0];
trgt.value=trgt.value.replace(RegExp(elm.getAttribute('name'), 'g'), elm.value);
}
Working jsfiddle demo here
you can use this code to do it:
$('firstTarget').onChange(function(){
var str = $('result').val();
str.replace(firstTarger, $( this ).attr('name'));
$('result').text(str);
}):
$('secondTarget').onChange(function(){
var str = $('result').val();
str.replace(firstTarger, $( this ).attr('name'));
$('result').text(str);
}):
$('thirdTarget').onChange(function(){
var str = $('result').val();
str.replace(firstTarger, $( this ).attr('name'));
$('result').text(str);
}):
enjoy!!!
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);
});
});