how to pass value dynamically in jquery - javascript

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 :)

Related

Call javascript function on enter of a text input, without using jquery

Is it possible to call a javascript function on enter of a text input, without using jquery?
<input name = 'text' type = 'text' onEnter('callJavascriptFunction')>
^---it would be preferable for the onEnter to be inside the element like above...
Sure is:
<input name="text" type="text" onkeyup="callJavascriptFunction();">
You can also do it without the inline javascript:
<input id="myTextBox" name="text" type="text">
Then in your js file:
var myTextBox = document.getElementById('myTextBox');
myTextBox.addEventListener('keyup', function(){
//do some stuff
});
Edit: If you're looking for enter press:
<input id="myTextBox" name="text" type="text">
Then in your js file:
var myTextBox = document.getElementById('myTextBox');
myTextBox.addEventListener('keypress', function(){
if(e.keyCode == 13){//keyCode for enter
//do some stuff
}
});
Use the event onchange. You can do this on HTML:
<input onchange="fncDoThings()">
And your JS file can be like this:
function fncDoThings() {
console.log('hello'); //just an example of things to do inside the function
};

jQuery : how to access the name of the element [duplicate]

This question already has answers here:
How to reach the element itself inside jQuery’s `val`?
(4 answers)
Closed last year.
Pls see the following html code
<input id="product_code1" name="Samsung"><br>
<input id="product_code2" name="Apple"><br>
<input id="product_code3" name="Huawei"><br>
<input id="product_code4" name="Motorola"><br>
and the jquery code
$( "input[id*='product']" ).val( 'test' );
the result will display 4 textbox with the value of 'test' as default, but now i like to display 4 textbox with the value of the product name, means first textbox will display 'Samsung', 2nd textbox will display 'Apple' & so on, so what command should i put in the jquery code ? pls advise.
Just use .val(fn):
$("input[id^='product_']").val(function() {
return this.name;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="product_code1" name="Samsung"><br>
<input id="product_code2" name="Apple"><br>
<input id="product_code3" name="Huawei"><br>
<input id="product_code4" name="Motorola"><br>
For each input element it will invoke the function that will return the value to set.
Bonus
To make it even more concise you could consider a helper function, e.g.:
jQuery.prop = function(name) {
return function() {
return this[name];
}
};
Then, the code becomes:
$("input[id^='product_']").val($.prop('name'));
Try this:
$("input[id*='product']").each(function() {
$this = $(this);
$this.val($this.attr("name"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="product_code1" name="Samsung"><br>
<input id="product_code2" name="Apple"><br>
<input id="product_code3" name="Huawei"><br>
<input id="product_code4" name="Motorola"><br>
$("input[id*='product']").each(function () {
var $this = $(this);
$this.val($this.prop("name"));
});
JSFiddle

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>

put html input values into javascript object

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);
});
});

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