开发者

How do I declare an input id tag as a variable in jquery?

开发者 https://www.devze.com 2023-02-01 17:59 出处:网络
$(\'<p><input type=\"text\" id = \"count\" value=\"Enter Item Name\"/></p>\') $(\'#counted\').text(count);
$('<p><input type="text" id = "count" value="Enter Item Name"/></p>')

$('#counted').text(count); 
$('#word').text($('#count').val());

Count is: <span id = "counted"></span>开发者_开发知识库

Word is: <span id = "word"></span>

what i'm trying to do is to print out what is in the current input labeled count. there are more than one inputs with the name count. i'm not sure how i am supposed to go about doing this.


Remember to use class not ID if you want to add more than one item, ID should always be unique. If you want to push it to an array you can use something like this (it's an example with 'Update' link to create the array):

In <head>:

$(function(){

    var mycountarray=[];
    var itemscount=$("input.count").size();
    $("a.update").click(function(){
        $("input.count").each(function(){
            mycountarray.push($(this).val());
        });
        return false;
    });

});

In <body>:

<input type="text" class="count" value=""/>
<input type="text" class="count" value=""/>
<input type="text" class="count" value=""/>
<input type="text" class="count" value=""/>

<a href="javascript:;" class="update">Update</a>

You're saving the .count count in itemscount and mycountarray will store values from those inputs, i.e. for values a, b, c, d you'll get an array: ["a", "b", "c", "d"]

mycountarray[0] = value of first input.count
mycountarray[1] = value of second input.count
mycountarray[2] = value of third input.count
mycountarray[3] = value of fourth input.count

I'm not sure it that's exactly what you're looking but hopefully it is :) Cheers G.


Consider providing more information in your question.

Assuming that by current input labeled count you mean currently selected/focused input and you want to display value of that input inside <span id="word"></span>

<input type="text" class="count" id="count1" />
<input type="text" class="count" id="count2" />
<input type="text" class="count" id="count3" />

<span id="word"></span>

jQuery:

$('.count')
  .focus(function() {
    $('span#word').text($(this).val())
  })
  .blur(function() {
    $('span#word').text('Please select an input');
  })

This will display value from currently focused input in span, and display "Please select an input" text if no input is focused (selected)

Here's an example: http://jsfiddle.net/nev3rm0re/Lju5U/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号