Davide
Davide

Reputation: 127

Jquery selector with variable as parameter

i have a problem with this code line:

alert($('input' + ' #' + $id_bici).attr('value'));

the HTML code is:

<input type="hidden" id="id_bici1" name="id_bici1" value="9">

the alert result is "undefined"

Upvotes: 3

Views: 91

Answers (5)

Gosha_Fighten
Gosha_Fighten

Reputation: 3858

Element1 Element2 is a selector that selects all Element2 inside Element1. So, "input #id" will select a element with id inside inputs. It's not your case. You already know the element id. Just use it.

$("id_bici1")

See CSS Selector Reference for a basic list of selectors.

var $id_bici = "id_bici1";
    alert($('#' + $id_bici).attr('value'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="id_bici1" name="id_bici1" value="9">

Upvotes: 1

jossiwolf
jossiwolf

Reputation: 2175

There's a space too much:

alert($('input' + ' #' + $id_bici).attr('value'));

should be

alert($('input' + '#' + $id_bici).attr('value'));

Upvotes: 1

dexhering
dexhering

Reputation: 422

You could do this:

alert($('#id_bici1').attr('value'));

Upvotes: 1

Ganov13
Ganov13

Reputation: 367

var yourId = 1;
alert($('input' + '#id_bici' + yourId).attr('value'));

with yourId is 1 in your sample code.

Upvotes: 1

Peter Rasmussen
Peter Rasmussen

Reputation: 16922

You have a space between input and #. If you want the input with the specific id. Then there should not be a space between them.

var $id_bici = 'id_bici1'; //added for full example
alert($('input' + '#' + $id_bici).attr('value'));

Upvotes: 8

Related Questions