开发者

jQuery - How do I test what type of selector is passing the value?

开发者 https://www.devze.com 2023-04-06 17:49 出处:网络
I am using the latest and greatest jQuery.I am trying to make my code efficient and reusable throughout a specific site and want consolidate a block.

I am using the latest and greatest jQuery. I am trying to make my code efficient and reusable throughout a specific site and want consolidate a block.

I have a piece of code that listens for a save button being clicked. When the save button is clicked, it figures out which selector was click and gets its id and value.

This code works perfectly for text boxes. I just want to be able to run select boxes, radio buttons, and check boxes through it too. I need to handle the data differently depending on whether it's a checkbox, radio, or text field.

If I know the id of a selector, how can I easily test which 开发者_C百科type of selector it is?

In pseudocode:

if (SelectorType == 'radio') {
    // do radio stuff
} else if  (SelectorType == 'text') {
    // do test field stuff
} else if  (SelectorType == 'checkbox') {
    // do checkbox stuff
}

ANSWER

This is what I was trying to get at:

    var ThisField = $(this).parent().parent().children("td:eq(1)").children(":input").attr("id");

    var FieldType = $("#"+ThisField).prop("type");
    if (FieldType == "select-one") {
        alert("You are trying to save select box info!");
    } else  if (FieldType == "text") {
        alert("You are trying to save text info!");
    } else  if (FieldType == "checkbox") {
        alert("You are trying to save checkbox info!");
    } else  if (FieldType == "radio") {
        alert("You are trying to save radio info!");
    }


You could use event.target:

$('input, select').click(function(e){
   alert(e.target.type);
   switch(e.target.type){
       case "checkbox": 
           break;
        case "radio":
            break;
          //and so on
});

fiddle here http://jsfiddle.net/v6fFn/


Can't you just use this.type? http://jsbin.com/iwilog/edit


jQuery's prop method can give you the input type:

$("#foo").prop("type")

or even simpler:

document.getElementById("foo").type


A better approach.

Wrap up common logic into a function. Pass the appropriate information to the function and handle the logic appropriately.


You can filter by type,

$('#myinput:radio');
$('#myinput:text');
$('#myinput:checkbox');
0

精彩评论

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

关注公众号