Noob jQuery "$" function return question - javascript

HTML:
<input type="text" id="priceperperson1" name="priceperperson1" />
<input type="text" name="personsvalue1" class="countme" readonly="readonly" />
JS:
jQuery(document).ready(function($) {
$('div.pricerow input.countme').each(function(){
var id = this.name.substr(this.name.length-1);
alert($('input#priceperperson'+id));
this.value = parseInt($('priceperperson'+id).value) * parseInt($('countpersons'+id).value);
});
});
Shortened as possible. All I've in alert is "Object"... Value is NaN. I've tried to "parseInt" on id. I've tried:
$('[name=priceperperson'+id+']');
$('priceperperson'+id);
What I'm doing wrong?

You are retrieving jQuery objects when you do the $(..)
To get the value (string) use the .val() method.
so
alert( $('input#priceperperson'+id).val() );

You should probably put the $ in the function definition.
I'm guessing it's causing the $ variable to be re-defined, in the function -- and not point to the jQuery's $() function anymore.
I'm thinking about this one :
jQuery(document).ready(function($) {
Try using, instead :
jQuery(document).ready(function() {

When you are looping through jquery objects, I believe you have to use:
$(this).attr('name'); instead of this.name
also, to call values from objects you have to use $.val() or $.attr('attributename');
// Shortcut for doc ready
$(function()
{
// Loop through values
var id = $(this).attr('name');
alert($('input#priceperperson' + id).val());
});

Are you perhaps looking for .val()?
this.val(parseInt($('priceperperson'+id).val()));

All I've in alert is "Object"... Value
is NaN. I've tried to "parseInt"
Try giving a base to parseInt:
parseInt(variable, 10);

There are some mistakes... to get the value of a jQuery object you must use .val() method, not .value.
Then, the parseInt() requires, as second parameter, the radix. Something like:
...
this.value = parseInt($('priceperperson'+id).val(), 10) * parseInt($('countpersons'+id).val(), 10);
...

your code may contain errors
your code
id = lenght 1 OK
if id lenght > 1 ?? possible exception
priceperperson1 to priceperperson_1
# option # proposal
<input type="text" id="priceperperson_1" name="priceperperson_1" /> // => use "_"
<input type="text" name="personsvalue_1" class="countme" readonly="readonly" />
jQuery(document).ready(function($) {
$('div.pricerow input.countme').each(function(){
var id = this.name.split("_")[1]; // => get array value
this.value = parseInt($('[name=priceperperson_'+id+']').value()) *parseInt($('[name=countpersons='+id+']').value());
});
});

Related

ID with special characters with Jquery

I have a ID with special characters. I need to get the value of this input with JQUERY.
<input style="text-align:center; width:50px;" type="text" onKeyPress="jq(this.id);" value="5" id="adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG">
<script>
function jq(str) {
var id = str.replace(/[%#;&,\.\+\#*~':"!\^\$\[\]\(\)=>|\/\\]/g, '\\\\$&');
var value = $("#"+id).val();
alert(value);
}
</script>
I try with this, but i dont have response in the alert.
Help! please!
Normally you can use jQuery's escape sequence in a selector, \\, to escape special characters. However that won't work in this case as the id you have specified in the element is invalid as it contains spaces.
Due to that you will have to use the attribute selector in jQuery to retrieve it:
var $el = $('[id="adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG"]');
console.log($el.val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="text-align: center; width: 50px;" type="text" onKeyPress="jq(this.id);" value="5" id="adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG">
A much better solution would be to fix the id of your elements before they are output in to the page to remove the spaces and special characters.
Get the answer from fiddle here
I have written in both javascript & jquery. There is an option fot trying // before every special character in ID, but that doesn't worked for me. So on the other way you can get the answer. Check & let me know.
$("#clickID").on('click', function(){
getVal = $(document.getElementById('adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG')).val();
console.log(getVal);
alert(getVal);
});
function jq(str) {
var element = document.getElementById("adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG");
var value = $(element).val();
alert(value);
}

How to get values of each input field using jquery having same name?

I am trying to get the values of each of the input field that are under same set. Below is my code:
Input field 1:
<input type="text" maxlength="255" name="amount[]" >
Input field 2:
<input type="text" maxlength="255" name="amount[]" >
and so on....the number of fields are variable.
Now I want to get the values the user typed in each of the field that is named . How to do that in jquery?
I have tried following code but it returns nothing:
$("input[name=amount[]]").val();
you can get all values in an array
var values = $('input[name="amount[]"]').map(function(){
return this.value;
}).get();
console.log(values);
Demo ---> http://jsfiddle.net/BFjp5/
Since there are multiple element with same name you need indexing:
$("input[name='amount[]']")[0].value;
Here is demo
and for getting all elements values:
$("input[name='amount[]']").each(function (i,v) {
alert(this.value);
});
Here is demo
by javascript
function getValues(){
var ids=document.getElementsByName('amount[]');
var ary=new Array();
for(var i=0;i<ids.length;i++){
ary[i]=ids[i].value;
}
return ary;
}
$("input[name='amount[]']")
This will get you a set of elements. You can get value of each of those elements by iterating over them.
$("input[name='amount[]']").each(function(){
$(this).val();
});
Try to pass the attribute value as a string since [ and ] are meta-characters,
var values = $("input[name='amount[]']")
.map(function(){ return $(this).val() })
.get().join('');
DEMO
You don't!
The whole point of ID's in the DOM is that they are unique.

Get value of text box that have id with special character

I have a some text boxe with id that contains special character like '(' and ')' . when i am accessing value of this text boxe i am getting value as undefined .need solution of this problem ...
<input type="text" id="header_COUNT(SUBJECT)" onblur="javascript:setHeader();" disabled="disabled">
script is
function setHeader(){
var val=$('#header_COUNT(SUBJECT)').val();
console.log(val);
}
This is not such a complex selector. You can use getElementById:
var val=$(document.getElementById('header_COUNT(SUBJECT)')).val();
You can escape characters in jQuery with 2 backslashes \\
So reference it like:
$('#header_COUNT\\(SUBJECT\\)')
jsFiddle
Use the following code
function setHeader(){
var val=$('input[id="header_COUNT(SUBJECT)"]').val();
console.log(val);
}
jsbin
var id_with_special_chars = 'header_COUNT(SUBJECT)';
var value = $('input[id="'+id_with_special_chars+'"]').val();
alert(value);

Get the id of input on keyup

I have an input box...
<input type="text" id="search_member" onkeyup="lookup(this.value);">
When I type in the field, it will go to function lookup(). From there I want to get the id of this input. I tried...
var This_id = $(this).attr("id");
but this won't work. Any suggestions on how I can get the id?
Because you are passing this.value to your lookup() function. It's better to pass this to your function and then use arg.value to get the value and arg.getAttribute('id') for the id
<input type="text" id="search_member" onkeyup="lookup(this);">
function lookup(arg){
var id = arg.getAttribute('id');
var value = arg.value;
// do your stuff
}
Get rid of onkeyup="lookup(this.value);
<input type="text" id="search_member">
and then use
$(function(){
$("#search_member").keyup(function(e){
var This_id = $(this).attr("id");
});
};
$(document).keyup(function(e) {
if (e.currentTarget.activeElement != undefined) {
var id = $(e.currentTarget.activeElement).attr('id');
}
});
The problem there is you're not passing the element in, you're passing the value. You need to change it to this:
<input type="text" id="search_member" onkeyup="lookup(this);">
Then the rest of your code should work fine.
why dont you give the function lookup the THIS?
lookup(this);
then u can also use the code you suggested
To get the id you should use this.id not this.value. I hope it work with you

How to parse a variable in Javascript

I'm trying to use this code:
var field="myField";
vals[x]=document.myForm.field.value;
In the html code I have
<form name="myForm">
<input type='radio' name='myField' value='123' /> 123
<input type='radio' name='myField' value='xyz' /> xyz
</form>
But this gives me the error:
document.myForm.field is undefined
How can I get field to be treated as a variable rather than a field?
Assuming that your other syntax is correct (I havne't checked), this will do what you want:
var field="myField";
vals[x]=document.myForm[field].value;
In JS, the bracket operator is a get-property-by-name accessor. You can read more about it here.
Use the elements[] collection
document.forms['myForm'].elements[field]
elements collection in DOM spec
BTW. If you have two fields with the same name, to get the value of any field, you have to read from:
var value = document.forms['myForm'].elements[field][index_of_field].value
eg.
var value = document.forms['myForm'].elements[field][0].value
and, if you want to get value of selected radio-button you have to check which one is selected
var e = document.forms['myForm'].elements[field];
var val = e[0].checked ? e[0].value : e[1].checked ? e[1].value : null;
You have to do it like this:
var field = "myField";
vals[x] = document.myForm[field].value;
or even
vals[x] = document.forms.myForm.elements[field].value;
Based on your tags, it seems that you are using jQuery. If so, you can just do this and it will make your life much easier:
var vals = new Array();
$("form[name='myForm'] :radio").each(function() {
vals.push($(this).val());
});
:-D

Categories