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 false
inside 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 id
s 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>