最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using onclick event inside input tags in HTML to call a Javacscript function - Stack Overflow

programmeradmin2浏览0评论

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

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

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>

Share Improve this question asked Feb 13, 2016 at 12:34 DoenDoen 331 gold badge1 silver badge6 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

Yes, but a better option is to use event listeners. A full parison 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./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>

Have you considered using the pattern attribute that became available with html5? If you provide the pattern ( regex style ) then you get browser specific style notifications if a field's content violates the pattern - it also prevents the form from being submitted until the data is accepted according to the pattern.

To clarify @Daniel Cheung's answer - it does work and he should be credited for the answer ( very similar to what I'd have suggested ) ~ I did modify his code slightly but not to the extent that it changes the behaviour.

What has not been addressed is the actual submission of the form. If you change from a standard submit input button to a regular button you will need to submit the form using javascript, but you'd need to ensure that there were no errors in the form's content first.

<!doctype html>
<html>
    <head>
        <meta charset='utf-8'>
        <title>Form field onclick event listener</title>
        <script>
            window.onload = function() {
                var a = document.getElementById("tel");
                var out = document.getElementById("output");
                document.getElementById("bttn").addEventListener("click", js);

                function js() {
                  out.innerHTML = ( a.value.search(/[a-zA-Z]/) != -1 ) ? "Telephone numbers must not contain charachters, only numbers" : "The telephone number is Ok";
                }
            }
        </script>
    </head>
    <body>
        <form method='post' id='fred'>
            <label>Username:<input type='text' name='username' id='username' pattern='[a-zA-Z0-9\s]+' /></label>
            <label>Tel:<input type='text' name='tel' id='tel' pattern='[a-z0-9]{5,16}' /></label>
            <input type='button' name='subm' id='bttn' value='Submit' />
        </form>
        <output id='output'></output>
    </body>
</html>

A mon method of validating a form and submitting if there are no issues is to assign an onsubmit event handler to the form itself. The event handler would do whatever processing of the data is required and return either true or false depending on whether or not there were any errors.

eg:

<form method='post' id='fred' onsubmit='return validateform( this )'></form>

function validateform( form ){
    var errors=false;
    /* do tests, displays messages */
    return errors ? false : true;
}

As I mentioned, this is really Daniel's code - just expanded ~ he should get credit for his answer - just adding my 10cents worth ;-)

发布评论

评论列表(0)

  1. 暂无评论