Let's say I am validating forms using HTML5. So, if my input field is required, and invalid, I can change the CSS styles to reflect that using the following code:
input:required:invalid, input:focus:invalid {
color: red;
}
Now, how can I determine if an input element is required:invalid or focus:invalid using jQuery?
Something like this:
if ( $('#myInput') has the attribute invalid) { Do something }
Obviously, the condition in the if statement needs to be a condition. How can I figure this out? Thanks!
Could use native checkValidity() inside a filter. There is no jQuery selector for invalid
var invalidInputs = $('#myForm :input').filter(function() {
return !this.checkValidity();
}).each(function() {
console.log(this.name, ' error message is ', this.validationMessage)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input name="noValidation">
<input name="required_w_value" value="test" required>
<input name="required_no_value" required>
</form>
Related
Could you tell me how to achieve html input:
<input id="blablabla" required> using javascript
all web answers i have found suggest to write something like:
input.setAttribute('required','true');
input.setAttribute('required','');
input.required='true'
but them all give me something like:
<input id="blablabla" required=''>
or
<input id="blablabla" required='true >
and they doesn't work
Only html that works is <input id="blablabla" required>
Could you help me ?
Thanks
I found your example as well as the other answers working perfectly.
Are you sure you did the right thing?
Also you can put like this, it will work too!
myInput.setAttribute('required', 'required');
Example code:
Please click Add required and then click Submit
function addRequired() {
const myInput = document.getElementById('inputText');
myInput.setAttribute('required', 'required');
alert('Input has been added required!');
}
function removeRequired() {
const myInput = document.getElementById('inputText');
myInput.removeAttribute('required');
alert('Input has been removed required!');
}
<form>
<input id="inputText" type="text">
<button type="button" onclick="addRequired()">Add required</button>
<button type="button" onclick="removeRequired()">Remove required</button>
<button>Submit</button>
</form>
You can do this in any of the following ways:
const myInput = document.getElementById('blablabla');
myInput.required = true // Method 1
myInput.setAttribute('required', true); // Method 2
To get something like <input id="blablabla" required> you have to use the first method
If you're looking for the typical asterisk to appear, that's something you have to add manually, with JS or CSS. But if you check the attributes of the element (by inspecting the HTML of the page) you can see that the required attribute has been added.
When clicking theinviteButton, the input search bar should clear out, but it doesn't work with my current code.
Am I targeting the element incorrectly?
$("#inviteButton").click(function(){
var userName = $("#searchUser").val();
if (userName.trim() != "") {
if (userName == myUserName) {
$("#connectToBox").append("You can't invite yourself");
$("#searchUser").empty(); // Doesn't work
} else {
socket.emit("checkUserConnect", userName, function(data){
if (data.result === undefined) {
console.log("No name");
$("#connectToBox").append("User does not exist");
$("#searchUser").empty(); // Doesn't work
} else {
console.log("name exists");
$("#searchUser").empty(); // Doesn't work
$("#connectToBox").append("Invite send");
UserID = data.result.id;
socket.emit("connectToUser", myUserName, UserID, currentConversation);
}
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="connectToBox">
<label for="search-2">Type in username</label>
<input type="search" name="search-2" id="searchUser" value="">
Connect
</div>
To empty an input field you would normally use:
$('#searchUser').val('')
Empty is used to clear away child nodes from elements like divs or p tags, but not for inputs.
Reason for that is that the text within an input is not represented as a child node of the element and instead stored on an html attribute of the input tag. Hence .empty() does not work for clearing the value.
You can clear the input field by using
$('#searchUser').val('');
$('#searchUser').val('');
This will work fine according to your application.
The empty() method removes all child nodes and content from the selected elements. Src: W3Schools
According to your requirement you need to reset the value of an input field, for that we have val() function. You can assign an empty string and it will work fine.
Using empty() won't work here.
Check these examples -
empty() working correctly -
function emptyOperation(){
$("div").empty();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" id="input-field" value="Random string">
</div>
<button onclick="emptyOperation()">Check</button>
empty() as per your code [won't work] -
function emptyOperation(){
$("#input-field").empty();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" id="input-field" value="Random string">
</div>
<button onclick="emptyOperation()">Check</button>
Solution to your problem -
function emptyOperation(){
$("#input-field").val('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" id="input-field" value="Random string">
</div>
<button onclick="emptyOperation()">Check</button>
I am trying to achieve the reverse of the following form function. This is working in the reverse to how I want it to function. I would like to have the form elements disabled by default and then enabled when the "clicker" is pressed. I am experimenting with the following code without success. I have no problems with the HTML, my problem is getting the script to function the way that I want it to.
SAMPLE HTML FORM ELEMENTS
<input type='text'></input>
<input type='text'></input>
<input type='text'></input>
<div id='clicker' style='background-color:#FF0000; height:40px; width:100px;'></div>
This is the JavaScript I am trying:
$().ready(function() {
$('#clicker').click(function() {
$('input').each(function() {
if ($(this).attr('disabled')) {
$(this).removeAttr('disabled');
}
else {
$(this).attr({
'disabled': 'disabled'
});
}
});
});
});
Should use prop() not attr() for disabled.
You can also use prop(propertyName, fn) to create the loop and isolate instances
$(function () {
inputs_toggle_disable();//disable on page load, assumes none have disabled in markup
$('button').click(inputs_toggle_disable);
});
function inputs_toggle_disable() {
$('input').prop('disabled', function () {
return !this.disabled
});
}
DEMO
It looks like you're missing the disabled attribute from your HTML inputs, simply add the attribute as shown below:
<input type='text' disabled />
<input type='text' disabled />
<input type='text' disabled />
Your clicker button then will remove this attribute (See JSFiddle).
http://jsfiddle.net/xredrdur/
I'm currently making a registration page for a site and need to show a typical password confirmation message. How would I make a script to hide and show a div?
This is as far as I've got:
<html><head>
<script language="javascript">
function correctpassword()
var password="password"
var confirmpassword="confirmpassword"
if (password1 != password2)
{
showcss="unconfirmed"
}
else
{
showcss="confirmed"
}
</script>
</head>
<body>
<form>
<u>Personal Details</u>
First Name: <input type="text" id="firstname">
Last Name: <input type="text" id="lastname">
Date of Birth:
Gender: Male Female
<u>Login Details</u>
Email Adress:<input type="text" id="email">
Username:<input type="text" id="username">
<!--check avalibility-->
Password:<input type="text" id="password">
Confirm Password:<input type="text" id="confirmpassword">
<!--Javascript if "password" doesnt equal "confirm password" showcss passwords don't match-->
<button type="button" onclick="correctpassword()">Display Date</button>
</form>
</body>
</html>
PS:The variables may be wrong.
Assuming you are talking about hiding / showing a div, spanor other similar element in HTML, you can use the jQuery JavaScript framework. For example:
$('#element_to_show').show();
$('#element_to_hide').hide();
You can trigger the hide / show via events, e.g. key press or user leaving the input element, in jQuery as well.
Control your styles and appearance with className property that applied to class markup attribute.
Try to avoid .style property of the elements and add/remove some classes instead. It will give you more control and simplify maintenance in the future.
in css:
.show{
display:block;
}
.box{
display:none;
}
in html:
<div id="passConfirm"></div>
<div id="box"></div>
in your script:
var confirmEl,
confirmBox;
confirmEl = document.getElementById('passConfirm');
confirmBox = document.getElementById('box');
confirmEl.addEventListener('click', showBox, false);
function showBox () {
confirmBox.className += ' show';
}
As mentioned, you can use some libraries that helps to work with DOM or write your own functions helping to add and remove some classes, check for hasClass method etc.
I'm on my phone, hence the short answer.
Easiest way is to get the id of the element like document.getElementById and place that into a variable.
Then use the style property like
Obj.style.display = "none";
To hide it.
I'm trying to select dynamic ids when a user types something into the input fields. My app spits out the input fields in the following format:
<input id="student_1_first_name" />
<input id="student_1_last_name" />
<input id="student_2_first_name" />
<input id="student_2_last_name" />
<input id="student_3_first_name" />
<input id="student_3_last_name" />
etc.
For example, I tried doing this to select the end of the id string:
<script type="text/javascript">
$(document).ready(
function (){
$("input[id$=_first_name]").bind("keyup", run_some_function_here);
run_some_function_here();
$("input[id$=_last_name]").bind("keyup", run_some_function_here);
run_some_function_here();
}
);
</script>
When I do that, Jquery can't seem to select the input ids, so the functions don't run. Do you have any ideas on how I can select the ids correctly?
assign class to each input e.g <input id="student_1_first_name" class="input-class" />
then try this
$(function() {
$('input.input-class').each(function() {
var id = $(this).attr('id');
});
});
$("input[id$=_first_name]") looks like it should work.
Does this give them red borders?
$("input[id$=_first_name]").css({ border: '2px solid red' });
If it does, then the function is probably not being called properly. Are you using anonymous functions or passing a reference to an existing function?
Update
Does this work as intended?
$("input[id$=_first_name]")
.bind("keyup", function() { run_some_function_here(); });