Calling Javascript from a html form

后端 未结 6 425
眼角桃花
眼角桃花 2021-01-30 06:18

I am basing my question and example on Jason\'s answer in this question

I am trying to avoid using an eventListener, and just to call handleClick

6条回答
  •  滥情空心
    2021-01-30 07:02

    In this bit of code:

    getRadioButtonValue(this["whichThing"]))
    

    you're not actually getting a reference to anything. Therefore, your radiobutton in the getradiobuttonvalue function is undefined and throwing an error.

    EDIT To get the value out of the radio buttons, grab the JQuery library, and then use this:

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

    Edit 2 Due to the desire to reinvent the wheel, here's non-Jquery code:

    var t = '';
    for (i=0; i

    or, basically, modify the original line of code to read thusly:

    getRadioButtonValue(document.myform.whichThing))
    

    Edit 3 Here's your homework:

          function handleClick() {
            alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
            //event.preventDefault(); // disable normal form submit behavior
            return false; // prevent further bubbling of event
          }
        
      
    
    
    Which of the following do you like best?

    Slithy toves

    Borogoves

    Mome raths

    Notice the following, I've moved the function call to the Form's "onSubmit" event. An alternative would be to change your SUBMIT button to a standard button, and put it in the OnClick event for the button. I also removed the unneeded "JavaScript" in front of the function name, and added an explicit RETURN on the value coming out of the function.

    In the function itself, I modified the how the form was being accessed. The structure is: document.[THE FORM NAME].[THE CONTROL NAME] to get at things. Since you renamed your from aye, you had to change the document.myform. to document.aye. Additionally, the document.aye["whichThing"] is just wrong in this context, as it needed to be document.aye.whichThing.

    The final bit, was I commented out the event.preventDefault();. that line was not needed for this sample.

    EDIT 4 Just to be clear. document.aye["whichThing"] will provide you direct access to the selected value, but document.aye.whichThing gets you access to the collection of radio buttons which you then need to check. Since you're using the "getRadioButtonValue(object)" function to iterate through the collection, you need to use document.aye.whichThing.

    See the difference in this method:

    function handleClick() {
       alert("Direct Access: " + document.aye["whichThing"]);
       alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
       return false; // prevent further bubbling of event
    }
    

提交回复
热议问题