jQuery className and removeClass not working - javascript

I have the following condition in a long function:
if ( shipSet == true ) {
$("#" + shippingFields[i]).style.background = 'gray';
$("#" + shippingFields[i]).className = 'optional';
} else {
$("#" + shippingFields[i]).removeAttribute('style');
$("#" + shippingFields[i]).removeClass('optional');
}
the style lines work fine, whether true or false, but the className and removeClass lines aren't working. Any suggestions? Am I just not using them properly?

Since ("#" + shippingFields[i]) return a jQuery object.
You need to use addClass() and removeClass() instead:
if ( shipSet == true ) {
$("#" + shippingFields[i]).css('background','gray');
$("#" + shippingFields[i]).addClass('optional');
} else {
$("#" + shippingFields[i]).removeAttr('style');
$("#" + shippingFields[i]).removeClass('optional');
}
Also, you can use css() to set the styles of your elements.

You should use addClass (to add class to element) and removeClass (to remove class from element):
$("#" + shippingFields[i]).addClass('optional');
$("#" + shippingFields[i]).removeClass('optional');

if ( shipSet == true ) {
$("#" + shippingFields[i]).css('background','gray');
$("#" + shippingFields[i]).addClass('optional');
} else {
$("#" + shippingFields[i]).removeAttr('style');
$("#" + shippingFields[i]).removeClass('optional');
}

Try this, for adding class name use always $("#attributeID").addClass('ClassName');
if ( shipSet == true ) {
$("#" + shippingFields[i]).css('background','gray');
$("#" + shippingFields[i]).addClass('optional');
} else {
$("#" + shippingFields[i]).removeAttr('style');
$("#" + shippingFields[i]).removeClass('optional');
}

Related

Set automatically value in a textbox after autocomplete javascript

I have 4 textbox that are connected each other in my database, the values are: Name surname, team, society, country.
I have already created an autocomplete method for all the values; infact if i try to write a name/society ecc, the method search in the database if the values exist and recommend values. Another thing that i have already implemented is that if I select a name surname and a team (or other 2 values) it suggests you society and country or what you did not select that are collegated with the other values.
What do i have to do to set automatically the values, without using the select of the user(what i have to do to set automaticcaly the textbox value of the result of the query)? Thank you.
I am using Asp.net mvc and javascript.
Edit: this the code.
Html:
#{
string autocompletePrefix = "address";
}
<div class="form-group">
#Html.CustomLabelFor(model => model.PlayerId, new { #class = "control-label col-md-2" })
<div class="col-md-10" style="display:inline-flex;">
<div class="input-group">
#Html.TextBox("Player", null, null, new { #id = autocompletePrefix + "PlayerName", #class = "ui-autocomplete-input form-control" })
<span class="input-group-btn">
<button id="#autocompletePrefix-PlayerSearcher" class="btn btn-default" type="button">
<span class="glyphicon glyphicon-list" id="#autocompletePrefix-playerIconList"></span>
</button>
</span>
</div>
<div class="ui-autocomplete ui-front btn-group-vertical"></div>
#Html.HiddenFor(model => model.PlayerId, new { #id = autocompletePrefix + "PlayerId" })
#Html.ValidationMessageFor(model => model.PlayerId)
</div>
</div>
<script type="text/javascript">
$(document).on('ready readyAgain', function () {
address = AutocompleteTeamModule('#autocompletePrefix', '#Url.Action("GetHintsForPlayers", "Addresses", new { })', '#Url.Action("GetHintsForTeam", "Addresses", new { })', '#Url.Action("GetHintsForSocieties", "Addresses", new { })', '#Url.Action("GetHintsForCountry", "Addresses", new { })');
initMultipleSelection();
});
</script>
Javascript:
function AutocompleteTeamModule( _prefixHtmlId, _hintsForPlayer,_hintsForTeam,_hintsForSociety,_hintsForCountry)
{
init: function () {
$("#" + myObj.prefixHtmlId + "-PlayerSearcher").click(function () {
myObj.PlayerSearcherClick = true;
$('#' + myObj.prefixHtmlId + 'PlayerName').autocomplete("option", "minLength", 0);
var value = $("#" + myObj.prefixHtmlId + "PlayerId").val();
if( value != "")
$('#' + myObj.prefixHtmlId + 'PlayerName').autocomplete("search", $("#" + myObj.prefixHtmlId + "PlayerId").val());
else
$('#' + myObj.prefixHtmlId + 'CountryName').autocomplete("search", "");
$('#' + myObj.prefixHtmlId + 'PlayerName').trigger("focus");
$("#" + myObj.prefixHtmlId + "-PlayerLoader").toggleClass("hide", false);
$("#" + myObj.prefixHtmlId + "-PlayerIconList").toggleClass("hide", true);
$("#" + myObj.prefixHtmlId + "-PlayerCountry").toggleClass("hide", false);
$('#' + myObj.prefixHtmlId + 'PlayerName').autocomplete("option", "minLength", 2);
});
$("#" + myObj.prefixHtmlId + "PlayerName").autocomplete({
minLength: 2, autoFocus: true, source: function (term, resp) {
$.ajax({
type: "GET",
url: myObj.hintsPlayerUrl,
data: { "id": term.term + "-" + $("#" + myObj.prefixHtmlId + "PlayerId").val() },
success: function (data) {
$("#" + myObj.prefixHtmlId + "-PlayerLoader").toggleClass("hide", true);
$("#" + myObj.prefixHtmlId + "-PlayerIconList").toggleClass("hide", false);
myObj.PlayerNameData = data.slice();
resp(data, function (data) {
return data;
});
},
error: function (xhr, txt, err) {
iride_error_handler(xhr, txt, err);
}
})
},
select: function (e, data) {
var pa=$("#" + myObj.prefixHtmlId + "PlayerId").val();
$("#" + myObj.prefixHtmlId + "PlayerId").val(data.item.value);
$("#" + myObj.prefixHtmlId + "-PlayerLoader").toggleClass("hide", true);
$("#" + myObj.prefixHtmlId + "-PlayerIconList").toggleClass("hide", false);
pa = data.item.value;
e.preventDefault();
var teamisSet = $("#" + myObj.prefixHtmlId + "TeamId").val();
if (teamisSet == "")
$('#' + myObj.prefixHtmlId + 'TeamName').autocomplete("search", "-" + pa);
e.preventDefault();
var societyisSet = $("#" + myObj.prefixHtmlId + "SocietyId").val();
if (provinceisSet == "")
$('#' + myObj.prefixHtmlId + 'ProvinceName').autocomplete("search", "-" + pa);
e.preventDefault();
var countryisSet = $("#" + myObj.prefixHtmlId + "CountryId").val();
if(countryisSet == "")
$('#' + myObj.prefixHtmlId + 'CountryName').autocomplete("search", "-" + $("#" + myObj.prefixHtmlId + "CountryId").val());
e.preventDefault();
},
focus: function (event, ui) {
if (ui.item.value != " ") {
$(this).val(ui.item.label);
}
event.preventDefault();
}
});
}
You might provide some code samples or be more specific in what components you are using.
Maybe you can use just jQuery (javascript):
$('#textboxID').val('new value of textbox');
Elaborating on the JQuery suggestion-
I'd definitely like to see some code but based on what I think your code looks like,
If you're talking about changing the value of selectors based on user input on other selectors, you can use a switch or if else inside your click handler. If this is a very data-heavy process there's sure to be a more efficient way to do it but if this is small enough it would go something like this-
$('submitbutton').click(function() {
if ($('firstselector').val() == 'certain value') {
$('secondselector').val("associated value 1");
$('thirdselector').val("associated value 2");
} else if ($('firstselector').val() == 'another certain value') {
// so on and so forth
};
});
a switch, if too many options available- to clean up the code
$('submitbutton').click(function() {
switch ($('firstselector').val()) {
case: 'certain value'
$('secondselector').val("associated value 1");
$('thirdselector').val("associated value 2");
break;
case: 'another certain value'
// so on and so forth
break;
};
});

Jquery animate backgroundColor not working

I'm trying to have a background color fade in (and then eventually I'll want it to fade back out) when you click a button. I can get the background to change color with this:
$("#" + lblqty).css("background","#e9f1ff");
But when I try to use animate (like below), it doesn't work. Nothing happens and I don't even get a javascript error:
$("#" + lblqty).animate({ backgroundColor: "#e9f1ff"}, 800);
I put the code in JSFiddle so you can see it in action. What should happen is when you click on "item" or check the checkbox, a div should appear that shows "Quantity 1" and a + and - sign. When you click the + sign, it should increase the quantity by 1 and the background should change color. Here's the link: http://jsfiddle.net/ew52wyLm/1/
$(".calccheckbox").change(function() {
var checkid = $(this).attr("id");
var qtyid = "qty_" + checkid;
var lblqty = "qtylbl_" + checkid;
var aic = "aic_" + checkid;
if (this.checked) {
$(this).attr("value", checkid + "_1");
$("#" + qtyid).html("1");
$("#" + lblqty).show(300);
// $("#" + aic).css("background","#b6d1ff");
// $("#" + lblqty).css("background","#e9f1ff");
} else {
$(this).attr("value", checkid);
$("#" + qtyid).html("");
$("#" + lblqty).hide(300);
}
});
$(".calcaddbutton, .calcremovebutton").click(function(event) {
var button = $(this);
var checkid = $(this).attr("id");
checkid = checkid.slice(3);
var qtyid = "qty_" + checkid;
var qty = $("#" + qtyid).html();
var aic = "aic_" + checkid;
var lblqty = "qtylbl_" + checkid;
if (button.hasClass("calcaddbutton")) {
if (qty > 49) {
alert("You may only add 50 of each item");
} else {
qty++;
$("#" + qtyid).html(qty);
$("#" + checkid).attr("value", checkid + "_" + qty);
// $("#" + lblqty).css("background","#e9f1ff");
$("#" + lblqty).animate({
backgroundColor: "#e9f1ff"
}, 800);
}
}
if (button.hasClass("calcremovebutton")) {
if (qty < 2) {
$("#" + qtyid).html("");
$("#" + checkid).attr("value", checkid);
var lblqty = "qtylbl_" + checkid;
$("#" + lblqty).hide(300);
$("#" + checkid).attr("checked", false);
} else {
qty--;
$("#" + qtyid).html(qty);
$("#" + checkid).attr("value", checkid + "_" + qty);
}
}
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="additemcontainer">
<div id="aic_1170">
<label for="1170">
<input type="checkbox" class="calccheckbox" value="1170" name="items[]" id="1170" />Item</label>
</div>
<div class="qtylbl" style="display:none;" id="qtylbl_1170">Quantity: <span class="qty" id="qty_1170"></span>
<a href="#" class="calcaddbutton" id="add1170">
<div class="calcbuttoncontainer"><span class="calcbutton glyphicon glyphicon-plus">+</span>
</div>
</a> <span class="calcbutton glyphicon glyphicon-minus">-</span>
</div>
</div>
You cannot animate the background-color with jQuery's default animate function.
What you can do, however, is position another div with a different color underneath your original div, and then animate the opacity on the original div, so that the color of the underlying div shows through, instead.
You can animate background color using Jquery UI library.
Include your jquery library and the jquery ui library, and it should work.
http://jqueryui.com/animate/
As multiple people mentioned, this isn't possible to do with jQuery, but it is possible with Velocity.js. And Velocity.js animations perform much better, especially on mobile!

Prototype to jquery function

I have a function for updating multiple selects based on values of another select.
How can I edit this function to use it without prototype just with jquery ?
function replace(val) {
if (val != 0) {
$$('select.replace).each(function(e) {
var aa = e.value.split("_");
if (aa[0] = val) {
e.value = val + "_" + aa[1] + "_" + aa[2];
jQuery("select.replace").trigger("chosen:updated");
}
});
} else {
alert('Please select a valid value');
return false;
}
}
It's simple:
jQuery( 'select.replace' ).each(function() {
var aa = $( this ).val().split("_");
if (aa[0] = val) {
$( this ).val( val + "_" + aa[1] + "_" + aa[2] );
//...
Red more about jQuery val() method.
Try using .change() when the select value is changed.
$( ".target" ).change(function() {
// code here
});

How to set focus on textbox on linkbutton click using javascript

I have this java script function
function showHideSearchPanel(dv) {
var Header = dv == 'Charts' ? 'ChartSearch' : 'ReportSearch';
var div = "ctl00_ContentPlaceHolder1_dv" + Header;
var panel = "ctl00_ContentPlaceHolder1_pnl" + Header;
var hiddenField = "ctl00_ContentPlaceHolder1_hdn" + Header + "Mode";
// I try to add this code in js but it not work
**var serchtextbox = document.getElementById("ctl00_ContentPlaceHolder1_txtSearchName");
if (serchtextbox != null) {
serchtextbox.focus();
}**
// I try to add this code in js but it not work
if ($("#" + div).attr('display') != 'block') {
window.status = 'Expanding contents....';
$("#" + div).slideToggle("slow");
$("#" + div).attr('visibility', 'visible');
$("#" + div).attr('display', 'block');
window.status = 'Done';
}
else {
window.status = 'Collapsing contents....';
$("#" + div).hide("slow");
$("#" + div).attr('visibility', 'hidden');
$("#" + div).attr('display', 'none');
window.status = 'Done';
}
$("#" + hiddenField).attr('value', ($("#" + hiddenField).attr('value') == 'On' ? 'Off' : 'On'));
}
This is my simple menu
When click on search button i want set focu on search textbox which is in below image

Making a button unclickable until jQuery .load() has finished

I'm currently using the following code for my read more buttons:
$(document).ready(function() {
$("a.more-link").attr("href", "");
$("a.more-link").attr("onclick", "return false;");
$('.readmore').each(function(index) {
var $link = $(this);
$(".readmore").prependTo('.' + $link.attr("id") + ' > #bottominfo');
});
$('.readmore').click(function() {
var $link = $(this);
if ( $link.attr("alt") == "read more" ) {
$('.' + $link.attr("id") + ' > #maincontent').load($link.attr("title") + ' #mainarticle', function(index) {
$('.' + $link.attr("id") + ' > #maincontent').hide();
$('.' + $link.attr("id") + ' > #maincontent').slideToggle('slow');
});
$('.' + $link.attr("id") + ' > #maincontent').attr("class", $link.attr("id"));
$link.attr('alt','read less');
} else {
$('#'+ $link.attr("id") + ' > .' + $link.attr("id")).hide();
$link.attr('alt','read more');
}
return false;
});
});
The problem I'm having is that if the user double clicks (or more) on the button it calls the function multiple times.
How do I make the button non-clickable until the .load() have finished?
The easiest would be to add a loading class to the link. I have also just done a quick clean up on your code. I didn't look into how it works but i'm sure if you spend a bit more time you can make it a lot more efficient
$(document).ready(function() {
$("a.more-link").attr("href", "")
.attr("onclick", "return false;");
$('.readmore').each(function(index) {
var $link = $(this);
//wouldn't this call all the elements with "readmore" class????
$(".readmore").prependTo('.' + $link.attr("id") + ' > #bottominfo');
});
$('.readmore').click(function() {
var $link = $(this);
//check if it has already been clicked
if($link.hasClass("loading")) return false;
//add the loading class
$link.addClass("loading");
if ( $link.attr("alt") == "read more" ) {
$('.' + $link.attr("id") + ' > #maincontent').load($link.attr("title") + ' #mainarticle', function(index) {
$('.' + $link.attr("id") + ' > #maincontent').hide()
.slideToggle('slow');
//it's done now and we can remove the loading class so we can click it again
$link.removeClass("loading");
}).attr("class", $link.attr("id"));
$link.attr('alt','read less');
} else {
$('#'+ $link.attr("id") + ' > .' + $link.attr("id")).hide();
$link.attr('alt','read more');
//add it here as well
$link.removeClass("loading");
}
return false;
});
});
Tips: I notice you call the same selectors multiple times. Always check the api doc and see what the methods you are calling do return. Most of them do return the element back, so then you can call the next method without $()
Example: $("div").hide().slideToggle('slow');
Could you not just run the function on .load instead?
$(document).load(function() {
$("a.more-link").attr("href", "");
$("a.more-link").attr("onclick", "return false;");
$('.readmore').each(function(index) {
var $link = $(this);
$(".readmore").prependTo('.' + $link.attr("id") + ' > #bottominfo');
});
$('.readmore').click(function() {
var $link = $(this);
if ( $link.attr("alt") == "read more" ) {
$('.' + $link.attr("id") + ' > #maincontent').load($link.attr("title") + ' #mainarticle', function(index) {
$('.' + $link.attr("id") + ' > #maincontent').hide();
$('.' + $link.attr("id") + ' > #maincontent').slideToggle('slow');
});
$('.' + $link.attr("id") + ' > #maincontent').attr("class", $link.attr("id"));
$link.attr('alt','read less');
} else {
$('#'+ $link.attr("id") + ' > .' + $link.attr("id")).hide();
$link.attr('alt','read more');
}
return false;
});
});

Categories