I need to validate the length of a string in the inputbox. If the string is invalid it will trigger an onblur event. When this event is triggered, it must turn the label of the object associated with the trigger red. However, there is a css class that exist that contains the style, so I just need to change the class to that class.
The prefix is some value being passed in.
Here is sample code.
var input = $(this).val();
var findLabel = document.getElementById`enter code here`(prefix+'findLabel');
if(input.length < min || input.length > max){
//alert is to check the values for testing
alert('Value for selected country '+selectedCountry+' must be between '+min+' and '+max+' characters');
}
example
<div class="Value_s123" id="a1Values123" style="float:left;">
<span class="avalue" id="a1value">
<label class="classOff" id="a1ValueLabel">some value</label>
<span style="white-space: nowrap;">
<input id="a1CatchValue" maxlength="15" name="a1Value" onblur="requiredFieldValidation("a1Postal")" size="15" tabindex="13" type="text"><img alt="Required" height="9" id="a1ValueReqdImg" src="/img/icn_dia.gif" width="11">
</span>
</span>
</div>
I need to get the a1ValueLabel and the class classOff and turn it to classON
Use this:
$("#a1ValueLabel").removeClass("classOff").addClass("classOn");
Here's what I came up with. The script is run every time someone types, once it reaches more than 5 characters the script adds the class "classOn" to the label tag. If there are 5 or less characters, it removes the "classOn" and adds the "classOff" class.
This is not a sustainable way to do it however, if you wanted to run this script on multiple items.
$(document).ready(function(){
$('#a1CatchValue').on('keyup',function(){
if ($(this).val().length > 5) {
$('#a1ValueLabel').removeClass('classOff');
$('#a1ValueLabel').addClass('classOn');
}
else {
$('#a1ValueLabel').removeClass('classOn');
$('#a1ValueLabel').addClass('classOff');
}
});
});
Related
So I have a simple log in that requires a user to input values from a json file into two different text boxes ,when the user name and (in this case I have used ID as password) matches then an alert appears to say... "welcome"
After the .click function is carried out the users text still remains in the text box, how can I get both text boxes to appear blank after the .click function?
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#invalid").hide();
$("#loginbtn").click(function(event){
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
var name = $('#userName2').val();
var valid = false;
for (var i=0; i<jd.user.length; i++) {
if ((jd.user[i].ID == id) && (jd.user[i].name == name)) {
valid=true;
$('#loginalert').html('<img src="' + jd.user[i].imgpath + '"><br><p> Welcome: ' + jd.user[i].name + '</p><button type="button" id="btnhide" class="btn btn-primary btn-md">Hide</button>');
//show the alert after loading the information
$("#loginalert").stop().fadeIn('slow').animate({ opacity: 1.0 }, 3000)
$('#invalid').hide();
$('#btnhide').on('click', function(e){
//console.log('here');
e.preventDefault();
$('#loginalert').hide();
});
}
}
if (!valid) {
$('#invalid').fadeIn('slow');
$('#loginalert').hide();
}
});
}); });
username 1 and #username 2 are the text boxes - is there any way to get user name 2 to display in stars ****** when the user enters the password - this question is not that necessary but if i could also get that working that would be good.
thanks guys hope someone can help :)
is there any way to get user name 2 to display in stars ****** when
the user enters the password
You can use an input box with text property set as password. But that password masking character will be . instead of *. Not exactly sure, whether it will be a different character in some browsers.
<input type="password" id="txtPassword" />
text box to appear blank after .click function
You can set the .val() property of the jQuery objects of two those two textboxes.
$('#userName, #username2').val('');
Use <input type="password"> to show typing as stars.
Clear inputs by setting their value to be empty: $('#userName').val('');
And perhaps consider breaking your code down into a couple smaller functions so it's easier to follow.
document.getElementById("#myTextbox").value="";
This should get your textbox and set the value of it to "", which is blank.
Edit: JSFiddle
Another Method:
You can also add the script directly inside the button without using/creating a function.
<input id="inputId" type="name" />
<button onclick="document.querySelector('#inputId').value='';"> Clear </button>
Using querySelector:
<input id="inputId" type="name" />
<button onclick="click()"> Clear </button>
<script>
function click() {
document.querySelector('#inputId').value="";
}
</script>
I am trying to build a form using only JavaScript and jQuery. For one of the textboxes, I need to make it display as a date. And another as American Currency.
I have seen a few really cool forms before where it already has the " / /" symbols in there, and as you type the date, it falls perfectly into the symbols so you don't have to type them. Also, I need it to display as a date in the same format (mm/dd/yyyy) when a button is clicked. In addition, somehow, I need it where if no dates were entered, it displays nothing when the button is pushed.
EDIT:
Okay, so, after looking around online, I found a better way to describe what I am looking for for the date. It is exactly the same as the HTML5
<input type="date">
However, after clicking the button, I need it to display as MM/DD/YYYY and the HTML5 only allows YYYY-MM-DD which is NOT what I want.
So, how do I build a single textbox that has the same functions (I don't need the date picker) as the HTML5 "date", but with the display formate as MM/DD/YYYY after a button is clicked?
This sort of input is not trivial. There's some finesse that you'll need to do. First the HTML:
<div id="dateInput">
<input type="number" placeholder="MM" maxlength="2"/>/<input type="number" placeholder="DD" maxlength="2"/>/<input type="number" placeholder="YYYY" maxlength="4"/>
</div>
<div id="moneyInput">
$<input type="number"/>
</div>
Now basic CSS, we'll remove the borders from the inputs and instead add them to the containers:
input{
border:none;
background:transparent;
}
div{
border:1px solid #e0e0e0;
}
Here's the hardest part, the Javascript/jQuery. The money one should work natively but the date one will take some work.
$('#dateInput').on('input', function(){
//get max length of the input
var maxLength = parseInt($(this).attr('maxlength'));
//get the current value of the input
var currentValue = $(this).val();
//if the current value is equal to the maxlength
if(maxLength == currentValue.length){
//move to next field
$(this).next().focus();
};
});
On button press gather all the values from the inputs and display
$('button').on('click', function(e){
e.preventDefault();
//set the variable to append ti
var dateDisplay = '';
//iterate over the inputs
$('#dateInput input').each(function(){
//if dateDisplay exists (will explain soon)
if(dateDisplay && $(this).val() != ''){
//append the value
dateDisplay += $(this).val() + '/';
} else {
//if the value is blank, make the variable false.
dateDisplay = false;
};
});
//now check the variable
if(dateDisplay){
//if it's all good, remove the last character (/) and display
alert(dateDisplay.slice(0,-1));
}
return false;
});
This doesn't check for validity, just handles the general UX.
I was browsing online and in other forums, and found this answer:
$('#date').keyup(function(){
if ($(this).val().length == 2){
$(this).val($(this).val() + "/");
}
else if ($(this).val().length == 5){
$(this).val($(this).val() + "/");
}
});
I have a hidden div with a simple form:
<div id="mb_clookup" style="display: none;">
<strong><font color="#0066CC">Search for existing customers</font></strong><br /><br />
<font color="#FFF">
Postcode: <input type="text" name="cl_zipcode" id="cl_zipcode" />
<span id="cl_search">Search</span>
</font>
</div>
This is displayed when the user clicks a button on the page. The user puts in the ZIP code, click on search and a JSON query is called. I have managed to make the Search button work with .live() but I cannot get the value of the input field. Here is the code:
$(document).ready(function(){
$(document).on( "click", "#cl_search", function() {
var pc = $('#cl_zipcode').val();
if(pc === '') {
alert('Please type in a post code first.');
}
else {
// JSON
}
});
});
Th pc variable comes up empty. I tried:$(this).find('#cl_zipcode').val() this comes up with undefined.
Please advise.
You can use the following
var pc= $("#mb_clookup").find('#cl_zipcode').val();
or
var pc= $("#mb_clookup :input").val();
check fiddle
With regard to $(this).find('#cl_zipcode').val() the input elements is beside the clicked span, so your find will search from the span on down (and it contains nothing aside from the text).
You need to move up the DOM first before you find it.
$(this).parent().find('#cl_zipcode').val()
Please note that as IDs are unique, so your original code is actually fine (so long as you only have one of these added): http://jsfiddle.net/TrueBlueAussie/djqfharu/
If you load more than one of these (you mention dynamic adding of fields) you will need to switch to classes to identify the elements.
e.g
$(document).ready(function(){
$(document).on( "click", ".cl_search", function() {
var pc = $(this).parent().find('.cl_zipcode').val()
if(pc === '') {
alert('Please type in a post code first.');
}
else {
// JSON
}
});
});
This is because browser keeps a fast-lookup dictionary, of IDs vs DOM elements, so only a single entry is retained per ID. The upshot of that is that jQuery can only ever find the first matching element for a search of a duplicated ID. The solution there is to switch to using classes and class-based searched.
I strongly suggest you post the rest of your code as the part shown is not the problem in isolation.
i thing your html code wrong. Becouse tag not in use tag
tag not support HTML5..
change this
<div id="mb_clookup" style="display:block;">
<strong><font color="#0066CC">Search for existing customers</font></strong><br /><br />
<span style="color="#FFF">
Postcode: <input type="text" name="cl_zipcode" id="cl_zipcode" />
<span id="cl_search">Search</span>
</span>
</div>
good luck
Your code is working fine i checked it in jsfiddle by removing display none attribute. You can check it here
HTML
<div id="mb_clookup">
<strong><font color="#0066CC">Search for existing customers</font></strong><br /><br />
<font color="#FFF">
Postcode: <input type="text" name="cl_zipcode" id="cl_zipcode" />
<button id="cl_search">Search</button>
</font>
</div>
JS
$(document).ready(function(){
$(document).on( "click", "#cl_search", function() {
var pc = $('#cl_zipcode').val();
if(pc === '') {
alert('Please type in a post code first.');
}
else {
alert(pc);
}
});
});
I am modifying existing code, so I can only affect the elements that exist rather an building it right. I am iterating over all spans that have the class reqd, and if so, I'm either taking the immediate previous sibling (example 1) or the previous sibling's first child of type input (example 2) and appending jQuery validate attributes to it.
Using prev() was for example #1, which was easy. I have to use prevUntil() for examples 2 and 3 to isolate better where I am targeting the DOM.
My issue is with example #2. While I can reach class="regfieldlabel I cannot get it to traverse its children. Example #3 is like #2 except with an empty span tag in the middle.
//Example code 1
<input type="text" name="str_cvv" value="" maxlength="3" size="4" id="CVV">
<span class="reqd">*</span>
//Example code 2
<span class="regfieldlabel">
<input type="text" name="nameOnCard" size="30" maxlength="50" id="cardName" value="">
</span>
<span class="reqd">*</span>
//Example code 3
<span class="regfieldlabel">
<input type="text" name="nameOnCard" size="30" maxlength="50" id="cardName" value="">
</span>
<span class="regfieldlabel"> </span>
<span class="reqd">*</span>
<script>
$(function() {
$("span").each(function(){
//Highlight all fields that have a red asterisk at the end for validation
if ($(this).hasClass('reqd')) {
$(this).prev().attr('data-rule-required', true).attr('data-msg-required', 'This field is required');
$(this).prevUntil('.regfieldlabel').find('input').attr('data-rule-required', true).attr('data-msg-required', 'This field is required');
}
});
});
</script>
You don't want to use prevUntil, from the docs you will see:
Description: Get all preceding siblings of each element up to but not
including the element matched by the selector, DOM node, or jQuery
object.
As a result, $(this).prevUntil('.regfieldlabel') is actually empty.
For Example 2, you still want to use just prev:
$(this).prev('.regfieldlabel').find('input')
For a general solution, you will have to check which situation you are in, in order to do the correct thing:
$("span.reqd").each(function(){
var $this = $(this);
var $prev = $this.prev();
var $input = $([]); // init to empty
if($prev.is("input")){
// EXAMPLE 1
$input = $prev;
} else if($prev.is(".regfieldlabel")){
var $innerInput = $prev.find("input");
if($innerInput.length > 0){
// EXAMPLE 2
$input = $innerInput;
} else {
$prev = $prev.prev(".regfieldlabel");
$innerInput = $prev.find("input");
if($innerInput.length > 0){
// EXAMPLE 3
$input = $innerInput;
} else {
// unknown case, maybe do something here
}
}
} else {
// unknown case, maybe do something here
}
$input.attr('data-rule-required', true).attr('data-msg-required', 'This field is required');
});
http://jsfiddle.net/DVSeg/2/
I am trying to create one of those standard new password forms, where you type the new password once and then a second time to confirm. I would like it so that once you blur away from these fields, if they don't match, both will be marked invalid, as in the following scenario:
User enters password abc into #newpassword1.
User tabs to #newpassword2.
User enters password def into #newpassword2.
User tabs away.
Validation detects a mismatch, and marks both #newpassword1 and #newpassword2 as invalid.
I know that i can mark the target of an event as invalid by using e.target.setCustomValidity(...), but i don't understand JavaScript's event model very well and can't figure out how to mark a different element as invalid based on the event target's own invalidity.
This is the relevant excerpt of (non-working) code that i am trying to use:
if ( $('#newpassword1').val() != $('#newpassword2').val() ) {
errorMessage = "The new passwords you've entered don't match.";
$('#newpassword1, #newpassword2').setCustomValidity(errorMessage);
}
This seems like it should work, intuitively, but of course it does not. The error is simply TypeError: $(...).setCustomValidity is not a function.
Please note: I am not asking how to add a red ring or whatever to a field, i want it to actually be invalid (as in, have its validity.valid property return false).
Is it possible to do this?
Thanks!
Try the below code. You are getting that error because jQuery returns an array of selected objects and since setCustomValidity is supported by native input elements and not jquery objects, you are seeing that error.
$('#newpassword1, #newpassword2').each(function() {
this.setCustomValidity(errorMessage)
});
<div class="cabinet_settings_header cabinet_header">Список регионов работы для выбора</div>
<div class="registration_region_select checkbox-group required">
<?for($i = 0; $i < sizeof($regions); $i++):?>
<label for="region_id_<?=$regions[$i]['region_id']?>">
<input type="checkbox" name="region_id[]" value="<?=$regions[$i]['region_id']?>" id="region_id_<?=$regions[$i]['region_id']?>" />
<?=$regions[$i]['name']?>
</label>
<?endfor;?>
</div>
<div class="cabinet_settings_header cabinet_header">Проверка выбора регионов работы (разрешмет отправку формы, если минимум 1 выбран)</div>
$('.checkbox-group.required input').on('change', function(){
checkRegions();
});
function checkRegions(){
checked_counter = $('.checkbox-group.required :checkbox:checked').length;
if(checked_counter > 0){
$('.checkbox-group.required #region_id_2')[0].setCustomValidity('');
}else{
$('.checkbox-group.required #region_id_2')[0].setCustomValidity('Выберите хотябы 1 из вариантов');
}
}
$(document).ready(function() {
checkRegions();
$("form").submit(function(event){
if($('.checkbox-group.required :checkbox:checked').length <= 0 ){
$('.checkbox-group.required #region_id_2').focus();
event.preventDefault();
}
})
});