-2

i want the event to happen only on to the username input type but it is occurring on each and every input type on the page. I need spaces to be restricted only in the username and not in other fields. Please provide with the appropriate event or event restriction technique.

Javascript:

<head><script>
$("myst()").on("onmouseover", function (e) {
return e.which !== 32;
});</script></head>

Html:

 <input type="text" name="fname" placeholder="First Name">
  <input type="text" name="lname" placeholder="Last Name"><br>        
  <input type="text" name="username" onmouseover="myst()" size="56" placeholder="User Name"><br>
  <input type="text" name="email" placeholder="Email Address">
  <input type="text" name="email2" placeholder="re-enter your Email Address"><br>
  <input type="password" name="password" placeholder="Password"><br>
Sanchit Gupta
  • 77
  • 1
  • 3
  • 10

1 Answers1

1

Not sure what your trying to do. Seems like trying to prevent white-space.

jQuery (with jQuery we assign the event keypress to input[name=username]):

$("input[name=username]").on("keypress", function(e) {
  var keyCode = (window.Event) ? e.which : e.keyCode;
  return keyCode !== 32;
});
.form-group {
  margin-top: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="form-group">
  <input type="text" name="fname" placeholder="First Name">
  <input type="text" name="lname" placeholder="Last Name">
</div>
<div class="form-group">
  <input type="text" name="username" size="56" placeholder="User Name">
</div>
<div class="form-group">
  <input type="text" name="email" placeholder="Email Address">
  <input type="text" name="email2" placeholder="Confirm Email Address">
</div>
<div class="form-group">
  <input type="password" name="password" placeholder="Password">
</div>

Pure JavaScript (with JS we assign the input (using name again since no Ids) a function to call your code):

document.getElementsByName("username")[0].onkeypress = function(e) {
  return (e.keyCode !== 32);
};
.form-group {
  margin-top: 15px;
}
<div class="form-group">
  <input type="text" name="fname" placeholder="First Name">
  <input type="text" name="lname" placeholder="Last Name">
</div>
<div class="form-group">
  <input type="text" name="username" size="56" placeholder="User Name">
</div>
<div class="form-group">
  <input type="text" name="email" placeholder="Email Address">
  <input type="text" name="email2" placeholder="Confirm Email Address">
</div>
<div class="form-group">
  <input type="password" name="password" placeholder="Password">
</div>

Should read about Attribute Equals Selector or Element.getElementsByTagName() and keypress

Also with jQuery their is many type of Selectors must common is $("#unique-id") which would look for element with an id="unique-id" or with JavaScript document.getElementById() which also takes a id value and looks for it on a element.

thekodester
  • 668
  • 4
  • 16