I have a simple case. I want two things.
Put label next to the input.
Some sort of validation, only digit number for the text box.
The corresponding link is here.
Now the input is below the label.
My code:
<div id="generatePinsDialog" title="Generate New PINs">
<label style="display: inline-block; width: 400px;">
How many?</label>
<input id="newInmateCount" type="text" size="25" value="Enter the number!" />
<br />
<select>
<option value="sameAsID">Same as ID</option>
<option value="appendID">AppendID</option>
</select>
Demo: http://jsfiddle.net/GCtPE/25/
label, input { display: inline-block; }
For verification you will have to use javascript since HTML5 isn't fully supported by all browsers. HTML5 is pretty cool though.
First, remove the "inline-block" from your label and add the for attribute like so:
<label for="newInmateCount" style="width: 400px;">How many?</label>
As for the input, do this for numeric only:
$("#newInmateCount").keydown(function(e) {
if (e.which == 8 || e.which == 46) return true; // for backspace and delete
if (e.which < 48 || (e.which > 57 && e.which < 96) || e.which > 105) return false;
});
See your jsFiddle Updated
Remove the display: inline-block. That is causing the input filed to go to new line.
You this js function to validate just digits, call it onkeypress event of the input field or bind it with onkeydown event
function onlyNumbers(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
jsFiddle demo
to put the label next to the input, change display:inline-block; to display:inline, or decrease the width:400px to a lower value until you acheive the positioning you want. for validation you need to do some reading on regular expressions
jsfiddle here
The input was so far to the right because you set the width of the label to 400px, I just removed that and it looks fine now. Also added some quick validation, you'd obviously have to run the validation when the form is submitted.
<div id="generatePinsDialog" title="Generate New PINs">
<label style="display: inline-block;">
How many?</label>
<input id="newInmateCount" type="text" size="25" value="Enter the number!" />
<br />
<select>
<option value="sameAsID">Same as ID</option>
<option value="appendID">AppendID</option>
</select>
</div>
And the JS is below:
if($('#newInmateCount').val() != "") {
var value = $('#newInmateCount').val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var intRegex = /^\d+$/;
if(!intRegex.test(value)) {
errors += "Field must be numeric.<br/>";
success = false;
}
} else {
errors += "Field is blank.</br />";
success = false;
}
On-submit validation is pretty easy with jQuery. Here's an example. If you want to keep it from ever having something other than numbers in it, you can go with an onchange or onkeyup event and simply strip the numbers from the input.
For the positioning, try inline instead of inline-block.
Related
I want to empty the input value when another input value has changed.
I tried this code, but not working yet. Any idea to solve this issue?
Thanks in advance.
<div class="continer">
<input type="text" class="type" id="type" value="">
<input type="text" class="model" id="model" value="">
</div>
<script>
$("#type").on('keydown', function() {
var key = event.keyCode || event.charCode;
if( key == 8 || key == 46 )
$("#model").empty();
});
</script>
you can use change event to trigger the change event and .val() method to set the value of the other inputs , like that
<script>
$("#type").on('change', function() {
$("#model").val("");
});
</script>
Having a weird minor little issue with submitting an input field on a keypress event - specifically enter.
Following is my js code:
$(document).ready(function() {
$('#findMyCouncillor').on('keypress', function (event) {
var keycode = event.keyCode || event.which;
if(keycode == '13') {
var search = $(this).val();
console.log(search);
}
});
});
And relevant html:
<div class="input-group mb-3">
<input id="findMyCouncillor" type="text" class="form-control" placeholder="Search....">
<div class="input-group-append">
<span class="input-group-text"><i class="fas fa-search"></i></span>
</div>
</div>
The issue is that console.log(search); is working - but search is empty. console.log(typeof search) returns string - but it looks empty? It just console logs a blank line...is this expected?
Perhaps the above code is the wrong way entirely, essentially on enter I want to grab whatever value has been input into the search field...
it wont submit even though the fields are not empty
here's the form:
<form id="form" role="form" method='POST' action="user_add-post.php">
<div class="form-group">
<p><label class="control-label">Title</label><br />
<input style="width: 40%" class="form-control" type="text" name="postTitle"/>
</div>
<div class="form-group">
<p><label lass="control-label">Description</label><br />
<textarea name="postDesc" cols="60" rows="10"></textarea>
</div>
<div class="form-group">
<p><label>Content</label></p>
<textarea name="postCont" cols="60" rows="10"></textarea>
</div>
<input type='submit' name="submit" class='btn btn-primary' value='Submit'></form>
and here's my jquery to check if the input fields are empty:
$('#form').submit(function() {
if ($.trim($("#postTitle").val()) === "" || $.trim($("#postDesc").val()) === "" || $.trim($("#postCont").val()) === "") {
alert('All fields required');
return false;
} });
now why won't it submit? it keeps on saying that all fields are required even though I already fill up the fields.
You have missed to add id in input boxes,
<input style="width: 40%" class="form-control" type="text" name="postTitle"/>
Change it to
<input style="width: 40%" class="form-control" type="text" id="postTitle" name="postTitle"/>
for next text box aswell ,Please Refer
you do not have define the ids so change the condition to
if ($.trim($('[name="postTitle"]').val()) === "" || $.trim($('[name="postDesc"]').val()) === "" || $.trim($('[name="postCont"]').val()) === "")
You have not given the ids to any of your form field, use global selector with condition
here is the working fiddle of your task
`$("input[name=postTitle]").val()` //name selector instead of id
If condition should be like this:
if ($("#postTitle").val().trim() == "" || $("#postDesc").val().trim() == "" || $("#postCont").val().trim() == "") {
See for any JS errors if you are getting. Also , try it on various browsers. You are not using ID attribute, but Name attritute, so it may not work on Firefox,Chrome and may work on IE7 and below. Hope this helps you
Provide Id to input element in html code.
Jquery code is fine
here is the correct code of html
<input style="width: 40%" class="form-control" type="text" name="postTitle" id="postTitle"/>
Yes like everyone else is saying if you are going to use selectors then you need those id's on the form fields. Or you can use the names like this:
$("[name=postTitle]").val()
$("[name=postDesc]").val()
$("[name=postCont]").val()
Here is your jquery with the above:
$('#form').submit(function() {
if ($("[name=postTitle]").val().trim() == "" || $("[name=postDesc]").val().trim() == "" || $("[name=postCont]").val().trim() == "") {
alert('All fields required');
return false;
} });
As others have said, the selectors are based on ID but using name attribute values. So you can add ID attributes, change the selector or use a different strategy.
Since the listener is on the form, this within the function references the form and all form controls with a name are available as named properties of the form. So you can easily test the value contains something other than whitespace with a regular expression, so consider:
var form = this;
var re = /^\s*$/;
if (re.test(form.postTitle.value) || re.test(form.postDesc.value) || re.test(form.postCont.value) {
/* form is not valid */
}
which is a lot more efficient than the OP.
Given the above, a form control with a name of submit will mask the form's submit method so you can't call form.submit() or $('#formID').submit().
In my code, I have the following javascript code block in the header section
function validateForm(bid) {
switch (bid) {
case "submitIDSearch":
alert("submitIDSearch");
return false;
case "submitNameSearch":
alert("submitNameSearch");
return false;
}
}
function fKeyDown(e) {
var kc = window.event ? window.event.keyCode : e.which;
if (kc == 13) {
document.getElementById('submitNameSearch').click();
}
}
Then I have the following HTML code block
<form name="checkAbsenceForm" method="post" action="absenceReport.htm" onsubmit="return validateForm(this.submited)">
<label class="q">ID * <input id="searchRUID" name="searchID" maxlength="9" /></label>
<input id="submitIDSearch" type="submit" value="Search ID" onclick="this.form.submited = this.id;" />
<hr />
<label class="q">First Name <input id="searchFirstName" name="searchFirstName" maxlength="23" onKeyDown="javascript:fKeyDown(event);"/></label>
<br />
<label class="q">Last Name * <input id="searchLastName" name="searchLastName" maxlength="23" onKeyDown="javascript:fKeyDown(event);" /></label>
<input id="submitNameSearch" type="submit" value="Search Name" onclick="this.form.submited = this.id;" />
</form>
What happened was that when I press Enter key in the searchLastName input text box, both alert message box pops up. One showing submitNameSearch and the other showing submitIDSearch. submitNameSearch is the desired event, but submitIDSearch is not, I think it is somehow triggered by default.
May I ask if there's a way to get rid of the submitIDSearch event when I press Enter key in the searchLastName input text box?
Thanks a lot!
When you press Enter in a form, the form is submitted. That's the reason of the second call to validateForm.
Two solutions :
1) Remove the onKeyDown="javascript:fKeyDown(event);" to have the normal validation defined on onsubmit=... apply.
2) In fKeyDown, add e.preventDefault(); to prevent the default handling of the key event :
function fKeyDown(e) {
var kc = window.event ? window.event.keyCode : e.which;
if (kc == 13) {
document.getElementById('submitNameSearch').click();
e.preventDefault();
}
}
But if you really do just this in fKeyDown, solution 1 is enough.
I have a html form with a select, button and an input element.
<form action="">
<button>innocent button</button>
<select multiple name="multiple">
<option selected value="a">A</option>
<option value="b">B</option>
</select>
<input style="width:300px" type="text" value="press here enter and look at the multiple select" name="" />
</form>
and some jquery javascript
$(document).ready(function(){
console.log('hi');
var $button = $('button');
$button.on('click',function(e){
$('select option').first().attr('selected',false);
e.preventDefault();
});
Demo: try it here:
http://jsfiddle.net/3Rjdh/
On Chrome everything is okay.
But on Firefox:
If you press ENTER in the input field, the select element loses it's selected.
What is wrong with Firefox?
When you press enter on the input, you are effectively firing the click event of the button, trying putting a conole.log in there and you'd see it fire
You can stop the submission by doing something this
function stopSubmit(e){
e = e || event;
return (e.keyCode || event.which || event.charCode || 0) !== 13;
}
Then in your form add the event for keypress
<form onkeypress="return stopSubmit(event)">
See the updated fiddle
I think, I fixed it by adding the attribute type with value button
http://jsfiddle.net/3Rjdh/2/