I have HTML construction like this
<div class="qn-block">
<input type="text" class="quantity-number" name="quantity-number" value="2" />
Refresh
</div>
For inputs with value > 1 i have to disable ".refresh-q". For inputs with value = 1 disable ".refresh-q" and ".remove".
How can I achieve this?
In order to disable an anchor you could define a click handler which returns false:
function disableAnchor() {
return false;
}
But you could also hide it or whatever.
and then:
$('.quantity-number').each(function() {
var value = parseInt($(this).val(), 10);
if (isNaN(value)) {
return;
}
if (value > 1) {
$(this).siblings('.refresh-q').addClass('disabled').click(disableAnchor);
} else if (value === 1) {
$(this).siblings('.refresh-q, .remove').addClass('disabled').click(disableAnchor);
}
});
Try this. You cannot disable a link, so I have simply hidden them. There are alternatives to simply hiding the element, such as removing the A element completely, or returning false when clicked, if you'd prefer to use those instead.
$(".quantity-number").change(function() {
var val = $(this).val()
if (val = 1) {
$(this).siblings(".refresh-q, .remove").hide();
}
else if (val > 1) {
$(this).siblings(".refresh-q").hide();
}
});
Related
I have a long if statement that I'm wanting to refactor. The statement listens for a click and then updates one of five text boxes depending on if those text boxes have anything in them or not. How could I change my code to be more efficient.
$('#img1').click(function() {
if ($('#card1').val().length === 0) {
$('#card1').val('A feeling of warmth');
} else if ($('#card2').val().length === 0) {
$('#card2').val('A feeling of warmth');
} else if ($('#card3').val().length === 0){
$('#card3').val('A feeling of warmth');
} else if ($('#card4').val().length === 0){
$('#card4').val('A feeling of warmth');
} else if ($('#card5').val().length === 0){
$('#card5').val('A feeling of warmth');
}
});
you could use a loop
$('#img1').click(function() {
var items = ["#card1", "#card2", "etc"];
for(var i=0;i<items.length;i++){
if ($(items[i]).val().length === 0) {
$(items[i]).val('A feeling of warmth');
}
}
});
it's at least easier to read. Also if your buttons are always card + a number you could make it even simplier (not easier to read, just less lines & maintenance)
$('#img1').click(function() {
for(var i=0;i<=5;i++){
if ($("#card" + i).val().length === 0) {
$("#card" + i).val('A feeling of warmth');
}
}
});
It seems like you're using JQuery. You can use a selector and a filter to isolate the first empty item:
$('#img1').click(function() {
$('input:text[id^=card]')
.filter(function() { return $(this).val() == ""; })
.first()
.val('A feeling of warmth');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="img1">CLICK ME</button><br>
<input id="card1"><br>
<input id="card2"><br>
<input id="card3"><br>
<input id="card4"><br>
<input id="card5">
$('input:text[id^=card]') selects all text inputs whose IDs begin with 'card'. But the same principle would apply to other element types.
$('#img1').click(function() {
// num can be total count of the element like $(.card).children.count
var num = 5, // preferably dont make it hardcoded.
str = 'A feeling of warmth',
preIdStr = '#card',
id;
for (var i = 1; i <= num; i += 1) {
id = preIdStr + i;
if ($(id).val().length === 0) {
$(id).val(str);
}
}
});
Give all cards the same class.
Then use the selector $('.yourclass')
Now use the jQuery for-each (.each) function to iterate all elements. Within the loop you check the value, set it to whatever you want and return false when the value was set, since this exit's the loop.
$('.yourclass').each(
function () {
if (this.val().length === 0) {
this.val('your value');
return false; // exit loop
}
});
I know it's easy to do using < button > or < input type="submit" but how would you keep this button disabled unless both input fields are filled?
<input id="one" type="text">
<input id="two" type="text">
OK
Tie an event to both inputs, and check that both have values. Then enable the link.
$('#one, #two').blur(function() {
if($('#one').val() !== "" && $('#two').val() !== "") {
$('.button').attr('href','#');
} else {
$('.button').removeAttr('href');
}
});
and change your html to:
<a class="button">OK</a>
so that the link is disabled on page load. Here's a JSFiddle demo.
$(document).ready(function() {
$inputs = $('#one,#tow');
$inputs.change(check);
$submit = $('#submit');
function check() {
var result = 1;
for (var i = 0; i < $inputs.length; i++) {
if (!$inputs[i].value) {
result = 0;
break;
}
}
if (result) {
$submit.removeAttr('disabled');
} else {
$submit.attr('disabled', 'disabled');
}
}
check();
});
suggest use angular form
$(document).ready(function(){
//$(".button").attr('disabled', "disabled");
$(".button").click(function(){
one = $("#one").val();
two = $("#two").val();
if(one && two){
///both fields filled.
return true;
}
//one or both of them is empty
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="one" type="text">
<input id="two" type="text">
OK
This is my implementation if facing this kind of situation.
First, am add disabled class onto anchor tag on page load by using this style :
.disabled {
color : gray // gray out button color
cursor : default; // make cursor to arrow
// you can do whatever styling you want
// even disabled behaviour
}
We add those class using jquery on document ready together with keyup event like so :
$(function () {
// add disabled class onto button class(anchor tag)
$(".button").addClass('disabled');
// register keyup handler on one and two element
$("#one, #two").keyup(function () {
var one = $("#one").val(),
two = $("#two").val();
// checking if both not empty, then remove class disabled
if (one && two) $(".button").removeClass('disabled');
// if not then add back disabled class
else $(".button").addClass('disabled');
});
// when we pressing those button
$('.button').click(function (e) {
// we check if those button has disabled class yet
// just return false
if ($(this).hasClass('disabled')) return false;
});
});
DEMO
I have this code that validates if ContentPlaceHolder1_locationTextBox has text in it before newIndex can become 3.
if ((newIndex === 3 && $("#ContentPlaceHolder1_locationTextBox").val() == "")) {
$('#ContentPlaceHolder1_locationLabelV').show();
return false;
}
else {
$('#ContentPlaceHolder1_locationLabelV').hide();
}
However I also have ContentPlaceHolder1_countryTextBox & ContentPlaceHolder1_seaTextBox on the page with thier respective labels, how can I modify the script so that it validates against all textboxes?
I tried adding a horrible or statement however this was causing the page to freeze. What s the best method to check against all three textboxes?
You can add class for all inputs, example: validate
After you can create JS function. You can fire this function as you wish.
function check(){
$('.validate').each(function(){
label = $("label[for='"+$(this).attr('id')+"']");
if ((newIndex === 3 && $(this).val() == "")) {
label.show();
return false;
}
else {
label.hide();
}
});
}
function validate(value) {
if ...
//show div
else ...
// hide div
}
$("input[type='text']").each(function(){
//value from input text field
var myval = $(this).val();
//call validation function
validate(myval);
});
I have a function that says if there are checkboxes with the value greater than 63, than show div, otherwise hide div.
function show_no_taxonomies() {
if ($('.store_checkbox:checked').val() > 63){
$("#hidden_taxon_message").show();
$("#hidden_taxon_message").text('This store does not have any texonomies');
}else {
$("#hidden_taxon_message").hide(); // something is selected
}
}
I need to redefine this conditional if statement to count the taxonomies. I have this tag attached to all of these checkboxes :
taxonomies_count="0"
I need the conditional statement to say if there are checkboxes with the taxonomies_count greater than 0, than show div, otherwise hide div.
<input id="idea_store_ids_" class="store_checkbox" type="checkbox" value="124"
taxonomies_count="0" name="idea[store_ids][]"></input>
This will do what you've asked...
function show_no_taxonomies() {
var taxonomiesCount = false;
$('.store_checkbox:checked').each(function() {
if ($(this).attr("taxonomies_count") > 0) {
taxonomiesCount = true;
return;
}
});
if (!taxonomiesCount){
$("#hidden_taxon_message").show();
$("#hidden_taxon_message").text('This store does not have any taxonomies');
}else {
$("#hidden_taxon_message").hide(); // something is selected
}
}
However, I'd recommend using a data attribute, rather than a custom attribute. Like this...
<input id="idea_store_ids_" class="store_checkbox" type="checkbox" value="124" data-taxonomies-count="0" name="idea[store_ids][]" />
and the script would be...
function show_no_taxonomies() {
var taxonomiesCount = false;
$('.store_checkbox:checked').each(function() {
if ($(this).data("taxonomies-count") > 0) {
taxonomiesCount = true;
return;
}
});
if (!taxonomiesCount){
$("#hidden_taxon_message").show();
$("#hidden_taxon_message").text('This store does not have any taxonomies');
}else {
$("#hidden_taxon_message").hide(); // something is selected
}
}
I solved this by logically simplifying my code by making 2 more large picture functions. Then, calling those functions into my larger function.
$(document).ready(function() {
$(".store_checkbox").change(function () {
$('div[store_id=' + this.value + ']').toggle(this.checked);
show_no_store_message();
}).change();
show_no_store_message();
});
function show_no_store_message() {
if (!is_store_selected()) {
$("#hidden_taxon_message").show(); // none are checked
$("#hidden_taxon_message").text('Please select store before selecting taxonomies');
} else if (is_store_selected() && !do_any_stores_have_taxonomies() ) {
$("#hidden_taxon_message").show(); // none are checked
$("#hidden_taxon_message").text('None of the stores you selected have taxonomies');
} else {
$("#hidden_taxon_message").hide(); // something is selected
}
}
// returns true if any store is selected
function is_store_selected(){
return ($('.store_checkbox:checked').length > 0);
}
// Returns true if any store selected AND store has taxonomiess
function do_any_stores_have_taxonomies(){
$('.store_checkbox:checked').each(function() {
if ($(this).attr("taxonomies_count") > 0) {
return true;
}
});
return false;
}
I have a (very) basic validation script. I basically want to check for any inputs with class .required to see if there values are a) blank or b) 0 and if so, return false on my form submit. This code does not seem to return false:
function myValidation(){
if($(".required").val() == "" || $(".required").val() == 0){
$(this).css({ backgroundColor:'orange' }) ;
return false;
}
}
Appending this function to my onSubmit handler of my form is not returning any results. Any light shed on this matter will be appreciated.
I am basically after a function that iterates through all the inputs with class .required, and if ANY have blank or 0 values, return false on my submit and change the background colour of all badly behaved inputs to orange.
Your code currently gets the .val() for the first .required, from the .val() documentation:
Get the current value of the first element in the set of matched elements.
You need to filter through each one individually instead, like this:
function myValidation(){
var allGood = true;
$(".required").each(function() {
var val = $(this).val();
if(val == "" || val == 0) {
$(this).css({ backgroundColor:'orange' });
allGood = false;
}
});
return allGood;
}
Or a bit more compact version:
function myValidation(){
return $(".required").filter(function() {
var val = $(this).val();
return val == "" || val == 0;
}).css({ backgroundColor:'orange' }).length === 0;
}
Try this jQuery selector:
$('.required[value=""], .required[value=0]')
You could also do it by defining your own custom jQuery selector:
$(document).ready(function(){
$.extend($.expr[':'],{
textboxEmpty: function(el){
return ($(el).val() === "");
}
});
});
And then access them like this:
alert($('input.required:textboxEmpty').length); //alerts the number of input boxes in your selection
So you could put a .each on them:
$('input.required:textboxEmpty').each(function(){
//do stuff
});