Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
112
rated 0 times [  115] [ 3]  / answers: 1 / hits: 17205  / 8 Years ago, sat, february 13, 2016, 12:00:00

Is it possible in HTML to insert onclick=function() like this:





<input type=submit  name=subm id=sub value=Submit onclick=js() />





After this submit button is pressed I want to call the function js() which is included in the script. This function makes a control if one of my input fields with tel id contains characters or not.After submitting the form nothing outputs. Can someone help with this code so it can output the message inside the js() function.





<script>
var a=getElementById(tel);
//tel is the id of a input field
function js(){

if((a.search(/[a-zA-Z]*/))!=-1){
document.writeln(Tel nr mustn't contain charachters);
}
else document.writeln(The tel number is Ok);

}
</script>




More From » html

 Answers
24

Yes, but a better option is to use event listeners. A full comparison of listener vs onclick is here: addEventListener vs onclick



JS:



var sub = document.getElementById(sub);
sub.addEventListener(click, js);


However! (Problem 1)



Do not use document.writeln(). That is because it will wipe the whole page clean if the function is triggered after loading the webpage. It is only meant for testing and not for productive usages. Please see: http://www.w3schools.com/jsref/met_doc_write.asp



On top of that! (Problem 2)



You need a type=button in your button to prevent the page from reloading!



Furthermore (Problem 3)



You cannot do a.search(). a is an element, while you can only do .search() on a string. To get the value of the input, you need a.value.



An then (Problem 4)



The regex won't work if you use /[a-zA-Z]*/. Try using /[a-zA-Z]/



Besides (Problem 5)



There is no getElementById() function. There is only a document.getElementById() method. I don't know if you have added your own, but currently, this won't work.






Please see this example (I fixed all you errors):





window.onload = function() {
var a = document.getElementById(tel);
var out = document.getElementById(output);
document.getElementById(btn).addEventListener(click, js);
function js() {
if (a.value.search(/[a-zA-Z]/) != -1)
out.innerHTML = Tel nr mustn't contain charachters;
else
out.innerHTML = The tel number is Ok;

}
}

<input type=text id=tel>
<button type=button id=btn>Click me :)</button>
<p id=output></p>




[#63330] Wednesday, February 10, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rhettforrestm

Total Points: 468
Total Questions: 106
Total Answers: 88

Location: Finland
Member since Sat, Nov 6, 2021
3 Years ago
;