开发者

Setting the value in a select dropdown using javascript

开发者 https://www.devze.com 2023-04-02 05:17 出处:网络
I am having trouble when trying to set a value in a select. I keep seeing NaN as my result (in some browse开发者_StackOverflow中文版rs - mainly android smartphone / tablet default browsers)

I am having trouble when trying to set a value in a select. I keep seeing NaN as my result (in some browse开发者_StackOverflow中文版rs - mainly android smartphone / tablet default browsers)

I am running a simply if statement and setting the value if the condition is true:

if (variable1 >= variable2)
{
    $('select[title="title"]').val(variable1);
}

Where a 'typeof' check on both variable1 and variable2 before the if statement show them both as numbers. Despite this the resulting value shown in select in the browser is NaN.

I've even tried wrapping the javascript Number() function around the variables like so:

if (Number(variable1) >= Number(variable2))
{
    $('select[title="myTitle"]').val(Number(variable1));
}

But I still get the same result!

Note: This works fine in desktop / laptop browsers and even Opera Mobile on my Samsung Galaxy S2 but as I'm working towards this being an app to run on any phone I wanted to be complete in my error checking.

edit: In case it's my select thats the problem (as suggested below) what's wrong with it here? Is it because it is converted to a string at the point I return it?

var startPoint = this.do_calcTotal(); // typeof startPoint shows as number
var endPoint = startPoint + 12; // typeof endPoint shows as number

var mySelect =   '<select title="myTitle" class="myClass">';

                    for (o=startPoint; o<endPoint; o++)
                    {
                        mySelect += '<option>'+Number(o)+'</option>'; // is this right?? it shows 'o' and 'Number(o)' as typeof number!?
                    }

mySelect += '</select></span></div>';

return mySelect;

Edit: and the code to add the current selected value to the span for display...

function do_changeNumberSpan(value)
{
    $('.mySpan').text(Number(value)); // even tried throwing a Number() round the value here!!
}


Ok. Check out this jsfiddle. This should help you understand a little bit of what your goal is... and how you can accomplish it. http://jsfiddle.net/aaronfrost/yFuyu/

0

精彩评论

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

关注公众号