How do I get these jQM 1.4 values out of a form wi

2019-08-30 00:25发布

I've got some settings I want to take out of a jQuery mobile 1.4 form to store in localStorage as the user settings for an app.

This is the form.

<form style="margin:0;padding:0;width:">                    
        <b>Age</b><br>        
        <input type="range" data-mini="true" data-highlight="true" name="ageview" id="ageview" min="0" max="99" value="30" >
        <p>                                                      
        <b>Gender</b><br>        
        <input type="checkbox" data-role="flipswitch" name="genderview" id="genderview" checked="" data-on-text="f" data-off-text="m" data-wrapper-class="custom-label-flipswitch" data-mini="true">                   
        <p>
        <b>Units<br><br>
        <label>
            <input type="radio" name="unit_choice" id="unit_choice" value="metric_units" data-mini="true" checked="true">&nbsp;cm / kg
        </label>
        <label>
            <input type="radio" name="unit_choice" id="unit_choice" value="imp_units" data-mini="true">&nbsp;inches / ibs
        </label>
    </form>

As you can see, the 3 items in question (Age, Gender and Units) are held in different types of input. I'm trying to get them into variable like this:

$("#settings_close").click(function(){
//get settings
var age_set = $("#ageview").val();
var gender_set = $("#genderview").val();
var units_set = $("#unit_choice").val();
alert("Age is "+age_set+". Gender is "+gender_set+". Units are "+unit_choice);
});

and I'm using the console to check them and get this output, regardless of what the Gender checkbox is set to.

Age is 30. Gender is on. Units are [object HTMLCollection] 

I've been experimenting with the val() and text() methods but I can't really get anything meaningful apart from the Age, which works fine. I must confess that I don't really understand what the "name" property in the inputs is for.

1条回答
爷的心禁止访问
2楼-- · 2019-08-30 01:19

First of all you should never have two elements on your page with the same id.

That said in order to get the value from your radio buttons you can instead try using the name attribute

For example

$('input[name=unit_choice]:checked').val()

For your checkbox (flipswitch) you will want to check to see if the value is checked, one way to do that is to see if the checked selector matches anything.

For example

var gender = $('#genderview:checked').length > 0 ? 'f' : 'm'; 

Alternatively you can check the checeked property directly like @ezanker mentioned

var gender = $("#genderview").prop("checked") ? "female" : "male";

To update the vales you would do something similar, except that in addition you need to tell JQM to update the markup by calling the appropriate refresh method.

For example

  $("#genderview").prop("checked", gender == 'f').flipswitch('refresh');

Update to the fiddle @ezanker provided

http://jsfiddle.net/N7jxY/2/

查看更多
登录 后发表回答