-2

I have a simple form:

<form name="demoForm" id="demoForm">
  <label id=”givenNameLabel” class =blueText>Please enter your given name:
  <input type = “text” name = “givenName” id= “givenName” value ="nn">
  </label>
  <button onclick = validate("givenName");>Validate this entry</button>
</form> 

But when I try to get the value it is undefined. I am getting the value either with vanilla JS or with jQuery:

<script type="text/javascript">
  function validate(someTextID){
       alert("In validate()")   //Works
       var thisElement = "#"+someTextID;         //the text element; 
       var thisLabel = thisElement + "Label"; //the label for the text element;                     
       var thisValue = $(thisElement).val(); //The value stored in the text box                                  
       alert("thisElement is " +thisElement);   //Works
       alert("thisLabel is " +thisLabel);       //Works

       alert("thisValue is " +thisValue);   //Why is the value undefined?

        //more code to take actions depending on thisValue 
  }
</script>
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
user2672224
  • 17
  • 1
  • 3
  • 3
    Use straight quotes `""` instead of “smart quotes” `“”`. – Sebastian Simon Sep 29 '19 at 15:25
  • What value are you seeing for `thisElement`? Does it match the ID of the input you want the value for? – Steve Sep 29 '19 at 15:29
  • Related: [Why is my code not working?](https://stackoverflow.com/q/20942773/4642212), [HTML class not being recognized](https://stackoverflow.com/q/46957500/4642212), etc. It works if you disable smart quotes in your editor and replace them by regular quotes. Please [validate your HTML](https://html5.validator.nu/) before posting. Don’t debug with `alert`; try using the [debugging capabilities](https://developer.mozilla.org/en-US/docs/Mozilla/Debugging/Debugging_JavaScript) of your browser. – Sebastian Simon Sep 29 '19 at 15:39
  • Inline event handlers like `onclick` are [not recommended](https://stackoverflow.com/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](https://stackoverflow.com/a/43459991/4642212) way of registering events. Always [use `addEventListener`](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Inline_event_handlers_%E2%80%94_don't_use_these) instead. – Sebastian Simon Sep 29 '19 at 15:39

1 Answers1

0

After straightening out your HTML a bit by replacing your "smart" quotation marks with "normal" ones (as Sebastian Simon mentioned in his comment) I simplified your code a bit and added a significant part:

  • return validate(...) in your onclick part makes sure that the return value from your validation function is used to determine whether to submit the form or not.
  • return falseinside your function will cause the form not to be transmitted (if you return true the form will be submitted)
    function validate(textid){
       console.log(document.querySelector('#'+textid).value);   //Works
       //more code to take actions depending on thisValue 
       
       return false;  // if you don't want to submit the form yet
    }
    <form name="demoForm" id="demoForm">
      <label id="givenNameLabel" class ="blueText">Please enter your given name:
      <input type="text" name = "givenName" id= "givenName" value ="nn">
      </label>
      <button onclick ='return validate("givenName")'>Validate this entry</button>
    </form> 

Here is an alternative version. I suspect, that you can probably do without the ids of the individual elements and you can re-use your validation function for other input fields, if you address the input fields in a "relative" way, i.e. by looking for a previousElementSibling of the clicked button.

The Array.prototype.forEach.call() is a clumsy looking construct that applies the Array method forEach() to the nodelist returned by document.querySelectorAll() (this version should even work in the Internet Explorer). Inside the forEach() function the click-event is bound to the validate(ev) function for each button with class "validate".

Array.prototype.forEach.call(document.querySelectorAll('.validate'),
  function(el){el.addEventListener('click',validate)});
function validate(ev){
  var el=ev.target.previousElementSibling;
  console.log('validating element '+el.name+', the value is: '+el.value);   
  //more code to take actions depending on el.name and el.value 
   ev.preventDefault(); // in case you DON'T want to submit the form yet ...
}
<form name="demoForm" id="demoForm">
  <label class ="blueText">Please enter your given name:
  <input type="text" name="givenName" value="Carsten">
  <button class="validate">Validate this entry</button></label><br>
  <label class ="blueText">Where do you live?
  <input type="text" name="myhome" value="Hanover">
  <button class="validate">Validate this entry</button></label><br>
  <label class ="blueText">What are your hobbies?
  <input type="text" name="myhobbies" value="coding">
  <button class="validate">Validate this entry</button></label>

</form>
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43