Prakash_se7en
Prakash_se7en

Reputation: 88

Fetch a user defined name using jQuery

Need to fetch the element by name using jquery , for fetching the name value, it is concatenated with samp (variable). cant able to form the name element. There is some problem with concatenation please help.

$("input[name^='resource_" + samp + "_']")

Full Code:

var samp = $(thisVal).attr('name');  //user defined name 

$("input[name^='resource_" + samp + "_']").each(function(key,val){
    alert("calcwk entered");
    if ($(this).val() === '') {
        theVal  = 0;
    }
    else {
        theVal = parseInt($(this).val());
    }
    tot = tot + theVal;
    alert("calcwk exit");
});

Upvotes: 0

Views: 86

Answers (3)

BinaryKitten
BinaryKitten

Reputation: 66

Since we cannot be sure of what the format the value "samp" will contain we need to make sure that the value is properly covered with right quotes.

$('[property=value]');

works as you have no spaces or anyway that the selector doesn't instantly know where the end of the property value is, whereas

$('[property=my value]');

confuses the parser for the system and as such you need to correctly "escape" or "wrap" the value with quotes eg:

$('[property="my value"]');

here's my version of your code for help

var samp = $(thisVal).attr('name'),   //user defined name 
    tot = 0                           //define the total
;

$('input[name^="resource_' + samp + '_"]').each(function(key,val){
    var theVal = $(this).val(); // do a jQuery call once per item
    if (theVal === '') {
        theVal  = 0; // if this is text change to 0
    }

    tot += parseInt(theVal); // no need with else, parseInt everything
    alert("calcwk exit");
});

As an example, I've created this JSFiddle: http://jsfiddle.net/fua9rtjd/

Upvotes: 5

lgabster
lgabster

Reputation: 715

Has name attribute the selected thisVal element? Here is the JsFiddle that works for me.

Upvotes: 1

viktor.svirskyy
viktor.svirskyy

Reputation: 479

Try:

var samp = $(thisVal).attr('name');  //user defined name 

$("input[name^=resource_"+samp+"_]").each(function(key,val){
        alert("calcwk entered");
        if( $(this).val() === '' ){
            theVal  = 0;
        }
        else{
            theVal = parseInt($(this).val());
        }
        tot = tot + theVal;
        alert("calcwk exit");
    });

Trouble with name like: '%name%' - don't need to use ' Right: $("input[name^=resource_"+samp+"_]")

Upvotes: 0

Related Questions