how to validate the input while entering the data using Jquery event?
$("#lname").blur(function() {
if ($("#lname").val().trim().match(/^[a-zA-Z ]+$/)) {
$("#lname").css({"border":"1px solid #cecece"});
$("#error_lname").css("display","none");
}
else{
$("#error_lname").css("display","block");
}
});
If you want to validate as the user types, use the input event instead of blur:
$("#lname").on('input', function() {
if ($("#lname").val().trim().match(/^[a-zA-Z ]+$/)) {
$("#lname").css({"border":"1px solid #cecece"});
$("#error_lname").css("display","none");
}
else{
$("#error_lname").css("display","block");
}
});
You should however note that to follow best practices you should avoid using css() and instead add/remove a class that's defined in an external stylesheet, something like this:
$("#lname").on('input', function() {
var $el = $(this);
var valid = $el.val().trim().match(/^[a-zA-Z ]+$/);
$el.toggleClass('invalid', !valid);
$el.next('.error-msg').toggle(!valid);
});
.invalid { border: 1px solid #CECECE; }
Note that the above is assuming the input you're validating has a following sibling which is the error message which has the class of .error-msg. Organising the logic in this way means that the validation logic can easily be genericised - instead of being tied to each control due to the #error_lname selector.
The answer of Rory is perfect I just want to add that you can also use onkeyup event also to get the same effect.
$("#lname").on('keyup', function() {
var $el = $(this);
var valid = $el.val().trim().match(/^[a-zA-Z ]+$/);
$el.toggleClass('invalid', !valid);
$el.next('.error-msg').toggle(!valid);
});
.error-msg{
display:none;
color:red;
}
.invalid{
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="lname">Last Name:</label>
<input type="text" id="lname">
<span class="error-msg">Error message here ...</span>
Related
I want to know if there is a way to add css on a required element in JavaScript I have many condition and i want it just in this case i want something like that (I know i can't do this)
Thanks for your help !
if (!allAreFilled) { // While required element are empty
alert('Fill all the fields');
objForm.style:required.border = "solid 1px red"; // objForm = document.getElementById('compoundFormId')
}
With css:
input:required {
border: 1px dashed red;
}
You cannot directly change CSS style settings for pseudo elements or classes in Javascript.
But you can set CSS variables from JS.
This snippet sets a CSS variable --border when the submit button is clicked with the value depending on a condition.
const button = document.querySelector('button');
let conditionIsSet = true;
button.addEventListener('click', function() {
document.body.style.setProperty('--border', (conditionIsSet) ? 'red' : 'black');
});
body {
--border: black;
}
input:required {
border: var(--border) 1px solid;
}
<input type="checkbox" onchange="conditionIsSet = !conditionIsSet;">Select condition is true</input>
<br> Input without required: <input> Input with required: <input required>
<button>Submit</button>
Obviously you need to supply whatever condition is needed.
I want to change the view of an object from a JS function depending on any events.
For example, I have a set of forms, including an input form of type text. While it is not completely filled, the color of the frame and font is green, when it is completely filled - red.
At the same time, I want to keep the freedom of the HTML designer and give him the opportunity to set class names arbitrarily. I want to operate at the subclass level.
I set this:
.info.available {
color: green;
border: 1px solid lime;
}
.info.full {
color: red;
border: 1px solid red;
}
And
<input class="info available" type="text" id="info">
I have a function myfunc(obj) that takes a pointer "this" and works with different components of a formset.
How for obj.form.info ... to switch the subclass from "available" to "full" and vice versa? How can I get its current value?
first, specify an input maxlength to know if its is completely filled or not.
<input class="info available" max-length="10" type="text" id="input">
then remove the outline color from your input field when it is clicked or being typed
input.available {
border: 1px solid green;
}
input.full {
border: 1px solid red;
}
input:focus {
outline: none;
}
this is to make .available and .full classes visible. then add an action event to your input field that will listen for every string that is typed. you can do it by:
next in your script tag, create the function that will be fired from your input field
<script>
function myfunc(e) {
let x = document.getElementById('input')
if (x.value.length == 10)
{
x.classList.remove('available')
x.classList.add('full')
}
else {
x.classList.add('available')
x.classList.remove('full')
}
}
</script>
x refers to your input field
x.value.length refers to the length of characters that is in your input field
if x.value.length is equal to your input's maxlength(which we specified as 10), it will replace the class .available by .full and vice versa
you can read the documentation or tutorials here:
https://www.w3schools.com/js/js_events.asp
https://www.w3schools.com/tags/ref_eventattributes.asp
Use maxlength="{maxlen}" for your input.
function myfunc(obj) {
if (obj.value.length >= maxlen) {
obj.classList.remove('available');
obj.classList.add('full');
} else {
obj.classList.add('available');
obj.classList.remove('full');
}
}
I found the following code here (Disable submit button unless original form data has changed) and it works but for the life of me, I can't figure out how to change the properties, text and CSS of the same submit button.
I want the text, background and hover background to be different when the button is enabled/disabled and also toggle another DIV visible/hidden.
$('form')
.each(function(){
$(this).data('serialized', $(this).serialize())
})
.on('change input', function(){
$(this)
.find('input:submit, button:submit')
.prop('disabled', $(this).serialize() == $(this).data('serialized'))
;
})
.find('input:submit, button:submit')
.prop('disabled', true);
Can someone please provide a sample. I have no hair left to pull out :-)
The answer you've copied isn't that great because a form doesn't have change or input events. Form elements do, instead. Therefore, bind the events on the actual elements within the form. Everything else looks okay except that you need to store the state of whether or not the stored/current data is equal to each other and then act accordingly. Take a look at the demo that hides/shows a div based on the state.
$('form')
.each(function() {
$(this).data('serialized', $(this).serialize())
})
.on('change input', 'input, select, textarea', function(e) {
var $form = $(this).closest("form");
var state = $form.serialize() === $form.data('serialized');
$form.find('input:submit, button:submit').prop('disabled', state);
//Do stuff when button is DISABLED
if (state) {
$("#demo").css({'display': 'none'});
} else {
//Do stuff when button is enabled
$("#demo").css({'display': 'block'});
}
//OR use shorthand as below
//$("#demo").toggle(!state);
})
.find('input:submit, button:submit')
.prop('disabled', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input name="tb1" type="text" value="tbox" />
<input name="tb2" type="text" value="tbox22" />
<input type="submit" value="Submit" />
</form>
<div id="demo" style="margin-top: 20px; height: 100px; width: 200px; background: red; display: none;">Data isn't the same as before!</div>
And the rest could be done via CSS using the :disabled selector(CSS3) or whatever is appropriate.
You can change the hover style of the button using css. CSS has hover state to target:
[type='submit']:disabled {
color: #ddd;
}
[type='submit']:disabled:hover {
background-color: grey;
color: black;
cursor: pointer;
border: none;
border-radius: 3px;
}
[type='submit']:disabled {
color: #ccc;
}
For showing and hiding, there are many tricks to do it. I think following would be the simplest trick to do and and easier for you to understand.
Add this in your html
<div id="ru" class="hide">this is russia</div>
<div id="il" class="hide">this is israel</div>
<div id="us" class="hide">this is us</div>
<div id="in" class="hide">this is india</div>
Add this in your css
.hide {
display: none;
background: red;;
}
Update your javascript like following:
$('form').bind('change keyup', function () {
.....
// get id of selected option
var id = $("#country-list").find(":selected").val();
$('.hide').hide(); // first hide all of the divs
$('#' + id).show(); // then only show the selected one
....
});
Here is the working jsfiddle. Let me know if this is not what you are looking for and I will update the answer.
The detection of change occurs on change input event.
You can change your code to the following in order to use this calculated value:
$('form')
.each(function(){
$(this).data('serialized', $(this).serialize())
})
.on('change input', function(){
var changed = $(this).serialize() != $(this).data('serialized');
$(this).find('input:submit, button:submit').prop('disabled', !changed);
// do anything with your changed
})
.find('input:submit, button:submit')
.prop('disabled', true)
It is good if you want to work with other divs. However, for styling, it is better to use CSS :disabled selector:
For example, in your CSS file:
[type='submit']:disabled {
color: #DDDDDD;
}
[type='submit']:disabled {
color: #CCCCCC;
}
I need something like a fill in the blanks sheet for children. When people click the ------ (dashes) it should turn into a textbox, and people can type it. after that when they move from that element after typing, it should turn into the text that they entered inside that text box.
I really dono how to approach this problem. I tried the following code, but what happens is, i am unable to type inside the text box. The cursor is not appearing at all
<html>
<head>
<title>NSP Automation</title>
<script src ="jquery.min.js">
</script>
</head>
<body>
<div class="container">
My Name is = <span id="name">__________<span>
</div>
<script>
$(document).on('click', '#name', function(){
document.getElementById("name").innerHTML = "<input type=\"text\">";
});
</script>
</body>
</html>
any pointers on how to achieve this ?
Thanks,
Since you've set the listener on the whole document, you will be recreating the input-tag with every click. Try something like:
$('#name').on('click', function(){
this.innerHTML = "<input type=\"text\">";
$('#name').off('click')
}
After clicking on the span-element, you remove the listener on it again, and you should be able to type.
http://jsfiddle.net/218rff9v/
Here is an example that generates the wished behaviour for all spans in your container. Some details can be improved but I think it's working as expected.
function convertSpanToInput() {
// Insert input after span
$('<input id="tmp_input">').insertAfter($(this));
$(this).hide(); // Hide span
$(this).next().focus();
$("#tmp_input").blur(function() {
// Set input value as span content
// when focus of input is lost.
// Also delete the input.
var value = $(this).val();
$(this).prev().show();
$(this).prev().html(value);
$(this).remove();
});
}
$(function() {
// Init all spans with a placeholder.
$(".container span").html("__________");
// Create click handler
$(".container span").click(convertSpanToInput);
});
Here is an html example with which you can test it:
<div class="container">
My Name is = <span></span>. I'm <span></span> years old.
</div>
JsFiddle: http://jsfiddle.net/4dyjaax9/
I'd suggest you have input boxes and don't do any converting
Simply use CSS to remove the borders and add a dashed border bottom
input[type=text]{
border:none;
border-bottom:1px dashed #777;
} <!-- something like that -->
add a click handler to add a edited class, so you can remove the bottom border
input[type=text].edited{
border:none;
}
That way you don't need to replace html elements, you just style them to look different
Why not use text input and only change CSS classes?
CSS:
.blurred{
border-style: none none solid none;
border-width: 0px 0px 1px 0px;
border-bottom-color: #000000;
padding: 0px;
}
.focused{
border: 1px solid #999999;
padding: 3px;
}
JavaScript:
$('#nameInput').focus(function(){
$(this).removeClass('blurred').addClass('focused');
});
$('#nameInput').blur(function(){
$(this).removeClass('focused').addClass('blurred');
});
HTML:
<div class="container">
My Name is = <span id="name"> <input id="nameInput" type="text" class="blurred"></input> <span>
</div>
Check this jsfiddle:
http://jsfiddle.net/gwrfwmw0/
http://jsfiddle.net/we6epdaL/2/
$(document).on('click', '#name', function(e){
if( $("#myText").is(e.target))
return;
$(this).html("<input type='text' id='myText' value='"+ $(this).html() +"'>");
});
$(document).on("blur", "#name", function(){
$(this).html( $("#myText").val() );
});
I'm trying to modify a contact form so that the submit button is disabled for five seconds after being clicked, to prevent accidental repeat submissions.
The problem is that disabling the button (by setting its 'disabled' attribute) prevents it from actually submitting. Setting any kind of even handler on them seems to override the default action, even though I'm not using .preventDefault();.
Is there a way I can bind a click event handler to a button that will operate in addition to its pre-existing functionality?
Here's the code I'm using:
jQuery(function() {
jQuery(":submit").on('click', function(e) {
jQuery(this).attr('disabled','disabled');
});
});
DEMO: http://jsfiddle.net/souviiik/4AsHc/
HTML
<form action="#" id="myForm">
<input type="text">
<input type="submit" value="Submit" class="btnSubmit">
</form>
JQUERY
var st;
$("#myForm").on("submit", function () {
if ($(".btnSubmit").hasClass("btnDisabled")) {
return false;
} else {
alert("clicked!");
$(".btnSubmit").addClass("btnDisabled");
st = setInterval(enableBtn, 5000);
}
});
function enableBtn() {
$(".btnSubmit").removeClass("btnDisabled");
clearInterval(st);
}
CSS
.btnSubmit {
background: #d33;
color: #FFF;
border: 1px solid #d33;
}
.btnDisabled {
background: #fefefe;
color: #aaa;
border: 1px solid #aaa;
}
if you want to use submit button only once you can use jquery .one() function