简体   繁体   中英

JavaScript/HTML - Assign a value to selected radio button

The case is basically like this:

I have 2 questions (have to answer both questions):
1. Do you smoke? a. Yes b. No
2. Do you drink? a .Yes b. No

If the user choose a. in question 1, then value will be 2
If the user choose b. in question 1, then value will be 1
If the user choose a. in question 2, then value will be 2
If the user choose b. in question 2, then value will be 1

After that, I will be sum up the value for selected radio buttons of both questions and display it.

The code for the radio buttons will be:

 <ul> <li>Do you smoke cigarettes?<br> <input type="radio" name="smoke" id="yes1" value="Y" checked="checked"> <label for="yes1">Yes</label> &ensp;&ensp; <input type="radio" name="smoke" id="no1" value="N"> <label for="no1">No</label><br> </li> <li>Do you drink?<br> <input type="radio" name="drink" id="yes2" value="Y" checked="checked"> <label for="yes2">Yes</label> &ensp;&ensp; <input type="radio" name="drink" id="no2" value="N"> <label for="no2">No</label><br><br></li> </ul> 
I know that the value in the radio button can be changed but I want to assign value in the javascript function. (The value in the radio button has it's own purpose.)

That's it. Even though I googled it around but still no solution that solve my problem. Any advice or suggestion will be appreciated.

Thank you in advance.

i think this is what you want. please let me.

   <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <script
    src="https://code.jquery.com/jquery-3.3.1.min.js"
    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
    crossorigin="anonymous"></script>
    <body>
        <ul>
            <li>Do you smoke cigarettes?<br>
                <input type="radio" name="smoke" id="yes1" data-vale = '2' value="Y" checked="checked">
                <label for="yes1">Yes</label> &ensp;&ensp;
                <input type="radio" name="smoke" id="no1" data-vale = '1' value="N">
                <label for="no1">No</label><br>
            </li>
            <li>Do you drink?<br>
                <input type="radio" name="drink" id="yes2" data-vale = '2' value="Y" checked="checked">
                <label for="yes2">Yes</label> &ensp;&ensp;
                <input type="radio" name="drink" id="no2" data-vale = '1' value="N">
                <label for="no2">No</label><br><br>
            </li>
        </ul>
        <input type="button" value="Get Value">
        <script type="text/javascript">
            $(document).ready(function(){
                $("input[type='button']").click(function(){
                    var radioValue = $("input[name='smoke']:checked").attr('data-vale');
                    var radioValue2 = $("input[name='drink']:checked").attr('data-vale');
                    console.log( parseInt(radioValue) +parseInt(radioValue2) )
                });

            });

            /*
            * OR if you dont want to change HTML and may be this will work for you
            *
            $(document).ready(function(){
                $("input[type='button']").click(function(){
                    var radioValue = $("input[name='smoke']:checked").val() == 'Y' ? 2 : 1;
                    var radioValue2 = $("input[name='drink']:checked").val() == 'Y' ? 2 : 1;
                    console.log( parseInt(radioValue) +parseInt(radioValue2) )
                });
            });
            */
        </script> 
    </body>
    </html>

Im not sure that i understand you right and i do not now why you want something like this. But this should work

<ul>
  <li>Do you smoke cigarettes?<br>
    <input type="radio" name="smoke" id="yes1" value="Y" checked="checked" onchange="yesSelected(this)">
    <label for="yes1">Yes</label> &ensp;&ensp;
    <input type="radio" name="smoke" id="no1" value="N" onchange="noSelected(this)">
    <label for="no1">No</label><br>
  </li>
  <li>Do you drink?<br>
    <input type="radio" name="drink" id="yes2" value="Y" checked="checked" onchange="yesSelected(this)">
    <label for="yes2">Yes</label> &ensp;&ensp;
    <input type="radio" name="drink" id="no2" value="N" onchange="noSelected(this)">
    <label for="no2">No</label><br><br></li>
</ul>

<script type="text/javascript">
  function yesSelected(input){
    input.value = 2
    console.log(input.value)
  }
  function noSelected(input){
    input.value = 1
    console.log(input.value)
  }
</script>

From my understanding you could satisfy this with a script that uses event listeners, specifically the change of value in your radio buttons. I would suggest also modeling a simple structure to capture your data. The following could be implemented. Instead of using an id for the question, associate them with an html data attribute. In this case we could specify something like data-question="1" . It would also be more practical to assign the value you intend to use on the input element from the start. So instead of using value="Y" try value="2" or value="1". Now that we have our html set up we will use another structure, this time to capture the value. We declare a const question of type array that holds objects. Each object represents a question, the id property is the value we associate with the data-question attribute on our input. To find the inputs we use the document.querySelectorAll(selector) method because two radio buttons share the same attribute. After we simply attach our eventlistener with a handler function that just update our answer for that question. if you wanted to add the result you could use a forEach method on the question const and log it to the console or present it where you find appropriate. Hope this helps

`

<ul>
  <li>Do you smoke cigarettes?<br>
    <input type="radio" name="smoke" data-question="1" value="2" checked="checked">
    <label for="yes1">Yes</label> &ensp;&ensp;
    <input type="radio" name="smoke" data-question="1" value="1">
    <label for="no1">No</label><br>
  </li>
  <li>Do you drink?<br>
    <input type="radio" name="drink" data-question="2" value="2" checked="checked">
    <label for="yes2">Yes</label> &ensp;&ensp;
    <input type="radio" name="drink" data-question="2" value="1">
    <label for="no2">No</label><br><br></li>
</ul>

<script>
const questions = [{id:1, answer:undefined},{id:2, answer: undefined}]

for(current of questions){
    let inputs = document.querySelectorAll('[data-question="'+current.id+'"]');
  for(input of inputs){
    input.addEventListener('change',function(e){ current.answer = e.target.value})
  }
}
</script>

`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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