将选定的值传递给jquery函数

pass selected value to jquery function

本文关键字:jquery 函数 值传      更新时间:2023-09-26

我正在尝试使用jquery删除<td>。如果<td>的联系人与用户从下拉列表中选择的联系人匹配,我需要删除它。问题是我不知道如何将这个值传递给函数。这是我的功能:

$(document).ready(function() {
    $("button").click(function() {
        $("td").each(function(index, paragraph) {
            $td = $(paragraph);
            if ($td.html() === "SELECTED GOES HERE") {
                $td.remove();
            }
        });
    });
});

这是下拉列表创建:

$query = "SELECT user_name FROM users";
$result = mysql_query($query); ?>
<select name="select1">
    <option value="" disabled selected>user name</option>
    <?php while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { ?>
        <option value="<?php echo $line['user_name'];?>">
            <?php echo $line['user_name'];?>
        </option>
    <?php } ?>
</select>

如何将选定的值发送到函数?谢谢

在函数中直接与所选值进行比较。

$(document).ready(function() {
    $("button").click(function() {
        $("td").each(function(index, paragraph) {
            $td = $(paragraph);
            if ($td.html() === $("#select1").val()) {
                $td.remove();
            }
        });
    });
});

要获得所选选项的值,只需执行以下代码:

$('select[name=select1]').val()

问候timotheus

您不必将值传递到函数中。单击按钮后只需获取选定的值。最简单的方法是使用:contains选择器

$(document).ready(function() {
    $("button").click(function() {
        $("td:contains("+$('select[name="select1"]').val()+")").remove();
    });
});

JSFiddle

你可能想进一步删除所选的选项(因为你可能不再需要它了):

$("button").click(function() {
    var val = $('select[name="select1"]').val();
    $('td:contains("'+val+'"), option[value="'+val+'"]').remove();
});

JSFiddle

我给你做了一把小提琴。我已经将您想要的内容传递给了一个ID,也将其作为变量传递给了您的函数

http://jsfiddle.net/37ocy2am/

HTML

<select name="select1" id="usernames">
    <option value="" disabled selected>user name</option>
        <option value="stephencarr">Stephen Carr</option>
        <option value="bobjones">Bob Jones</option>
        <option value="ashleysims">Ashley Sims</option>
        <option value="rushgreg">Rush Greg</option>
</select>
<div id="place_name_here">when you select you will get name here. <br>Just change jquery to pass the var somewhere else</div>

JS

$(document).ready(function() {
$( "#usernames" ).change(function() {
    var selected_value = $("#usernames").val();
    $("#place_name_here").html(selected_value);
    $("td").each(function(index, paragraph) {
            $td = $(paragraph);
            if ($td.html() === selected_value) {
                $td.remove();
            }
        });
});//close change function
});

CSS

#place_name_here{
    width:100%;
    text-align:center;
    font-weight:bold;
    font-size:20px;
    color:#00277A;
}