简体   繁体   English

使用jQuery获取文本或复选框的值并将其放入变量中

[英]Getting the value of a text or checkbox with jQuery and putting it into a variable

I have the following code: 我有以下代码:

$("input[id^='Order_'], input[id^='Default_']")
   .change(function (e) {
      var type = $(this).attr('id').split('_')[0];
      updateField('Menu', $(this), type);
});

The input with an id of 'Order_' has a type="text"
The input with an id of 'Default_' has a type="checkbox"

In my updateField I have a problem: 在我的updateField中我遇到了一个问题:

function updateField(entity, obj, type) {
    var val = obj.val();
    var idArr = obj.attr("id");
    var idTmp = idArr.split("_");
    var id = idTmp[1];
    var pkrk = $("span[id='refKey_" + id + "']").html();

The problem is that the code works good for the text but not for the checkbox. 问题是代码适用于文本,但不适用于复选框。 If the checkbox is checked or not then it still returns true. 如果选中或不选中该复选框,则它仍然返回true。 Is there a way that I can get the value of if the checkbox is checked or not and either put the string "true" or "false" into the variable val while still having the correct value put into val if the date is coming from the Order_ ? 有没有办法可以获得复选框是否被选中的值,并将字符串“true”或“false”放入变量val,同时仍然将正确的值放入val中,如果日期来自于订单_?

So if the value of Order_ field is 25 then val = "25"
So if the value of Default_ checkbox is true the val = "true"
So if the value of Default_ checkbox is false the val = "false"

The problem is that the checkbox doesnt have any "value". 问题是复选框没有任何“值”。 Instead of using the val() function in jQuery search for the attribute "checked". 而不是在jQuery中使用val()函数搜索属性“checked”。 This can be done as such: 这可以这样做:

var checked = !!$("checkbox selector").attr("checked");

Or using the jQuery selectors 或者使用jQuery选择器

var checked = $("checkbox selector").is(":checked");

So the attr() function will return undefined if the checkbox tag doesnt contain the attribute "checked" and that is the same as the unchecked state of the checkbox. 因此,如果checkbox标签不包含“已检查”属性且与复选框的未选中状态相同,则attr()函数将返回undefined。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM