使用JQuery更改标签文本

时间:2014-04-18 15:17:20

标签: javascript jquery select label

我希望每当用户从Metric更改为Imperial时标签都会更改。

它正确检测到更改并存储所选的当前值,步入if语句,但没有任何反应。

这是我的JavaScript。

$(document).ready(function() 
{   
    $("select[name = unit]").change(function()
    {
        var selected = $("option:selected", this).text();

        if(selected == "Metric (cm)")
        {
            $("label[for = unit]").text("mm");
        }
        else if(selected == "Imperial (inches)")
        {
            $("label[for = unit]").text("in");  
        }
    });
})

我的HTML。

    <form name ="Calculator">

        Unit of Measurement: 

        <select name = "unit">

            <option value = "120904000">
                Metric (cm)
            </option>

            <option value = "4760000">
                Imperial (inches)
            </option>

        </select>

        <br>


        Root Diameter: <input type = "text" name = "root" autocomplete = "off">
        <label for = "unit"></label>
        <br>

        Width between bearings: <input type = "text" name = "bearings" autocomplete = "off">
        <label for = "unit"></label>
        <br>

        End Fixity: 
        <select name = "fixity">

            <option value = ".36">
            1
            </option>

            <option value = "1.0">
            2
            </option>

            <option value = "1.47">
            3
            </option>

            <option value = "2.23">
            4
            </option>

        </select>

        <br>

        Max Speed (RPM): <input type = "text" name = "speed" autocomplete = "off"><br>

        <a href = "#" class = "reset" onclick = "">Reset</a>
        <a href = "#" class = "calculate" onclick = "checkOp(); return(false);">Calculate</a>
        <a href = "#" class = "close" onclick = "">Exit</a>

    </form>

1 个答案:

答案 0 :(得分:4)

我无法猜到你遗失的地方。但是检查这个js小提琴,我使用你的代码,它的工作对我来说绝对没问题。

Your code Fiddle

$("select[name = unit]").change(function()
    {
        var selected = $("option:selected", this).text().trim();

        if(selected == "Metric (cm)")
        {
            $("label[for = unit]").text("mm");
        }
        else if(selected == "Imperial (inches)")
        {
            $("label[for = unit]").text("inches");  
        }   });

我为你更新了jsfiddle。你需要在最后添加这个修剪:

var selected = $("option:selected", this).text().trim();

然后你就开始了。

这是更新的jsfiddle:

updated code fiddle