Jquery change color condition - javascript

Hi everyone I have an issue with Jquery :
I have a multiple selection and the user can select one thing and it will copy the text into an input above. I would like that the text in the multiple selection that will be copied become red if the button is clicked so did you understand? I don't know how to do condition in Jquery, here is what I have done :
$(document).ready(function(){
if ($choose = true)
{
$("ok").click(function(){
$("droite").css({"background-color":"yellow"});
}
});
});
droite is an id and no it's not working but I would like to know how it works
choose is a function here it is :
var choose = function(bouton){
var lesoptions = $('#droite').find(":selected");
//lesoptions.remove();
$('#numLot').val(lesoptions[0].text);
};
Can I have your opinion ?
thanks

$("ok") is wrong. it should be $("#ok") or $(".ok") or whatever.
compare operator is == instead =

Try to use like below,
var $Choose;
//Assign value to $Choose as like true or false
$(document).ready(function(){
if ($choose)
{
//If you have id like ok use "#" or if class use "." instead
$("#ok").click(function(){
$("#droite").css({"background-color":"yellow"});
});
}
});
Hope this helps...

You have to use . selector before class names and # before id names.
Read about selectors: jQuery Selectors
Since choose is a function so, you will have to return something and check if it returns true/false. So make your function like this:
function choose(bouton){
var something = /*your return value*/; //Put your return value here
var lesoptions = $('#droite').find(":selected");
$('#numLot').val(lesoptions[0].text);
return something; //something is what you want to be returned by function
};
If $choose is not defined while you are putting it in if condition then you will not get proper working.
If #ok is added dynamically then use delegation using .on.
You should put code like this:
$(document).ready(function(){
var $choose = choose(bouton);
if ($choose)
{
$("#ok").on("click",function(){ //Again not mentioned what is ok, still like you told I assume it id
$("#droite").css("background-color","yellow");
});
}
});

Related

Using .after but only if the value does not exist

I am running this code to insert a HTML line after the id #wp_menu:
$(document).on('closing', '.remodal', function (e) {
$('.menu_name').each(function() {
$('#wp_menu').after('<div class="tag">' + $(this).val() + '</div>');
});
});
The problem is, every time I run this loop, I'll get duplicated values and this is not what I want. How can I check if the code was inserted before?
This is a simple example that may explain my problem: https://jsfiddle.net/vLqonqpk/
So when you click on "add" multiple times, it will add the same values over and over again.
You could do something like this:
arr = [];
$('button').click(function() {
$('ul input').each(function() {
if ($.inArray($(this).val(), arr) == -1) {
$('#wp_menu').after('<div class="tag">' + $(this).val() + '</div>');
arr.push($(this).val());
}
});
console.log(arr);
});
DEMO: https://jsfiddle.net/vLqonqpk/1/
So, create array of values, check if current val(s) from inputs are duplicated, and place just unique values. Of course, you can add additional checks for empty string, and give user some alerts/warnings (create else block for that purpose), if needed, etc, etc...
But this is basic idea which should work.
Simply isolate the jQuery selector and check its existence.
$(document).on('closing', '.remodal', function (e) {
$('.menu_name').each(function() {
var $wp_menu = $('#wp_menu');
var $tag = $wp_menu.next('.tag'); // .siblings() also works
// Now you check if it exists, and create it if not
if (!$tag.length)
$tag = $('<div class="tag">').insertAfter($wp_menu);
// Simply update the content, element will always exist
$tag.text($(this).val()); // .html() also works
});
});
I'm sure there's several ways to do it, this is just one of them.
I now realize your problem is not duplicating tags, but values. Basically you want a HashSet. Please accept sinisake's answer instead

JQuery Fade Hidden Field In And Out On Select Change

I currently have this jquery code that is supposed to show and hide a field based on the content on what is selected:
$('#State').on('change', function() {
var s = $('#State option:selected').text;
if(s !== "")
{
$('#showme').fadeIn();
}
if(s === "")
{
$('#showme').fadeOut();
}
});
Here is a working fiddle: https://jsfiddle.net/b0h6xd0t/
It will fade the field in, but it won't fade it back out for some reason. Any ideas?
Thanks!
In jQuery, text() is method. Methods, in order to work, require the use of the parentheses as shown below:
var s = $('#State option:selected').text(); // I added: ()
Note: In JavaScript, the empty string is considered false. So for neatness, you can turn your code into the following:
$('#State').on('change', function() {
var s = $('#State option:selected').text();
if(s) { // If it's true
$('#showme').fadeIn();
}
else { // If it's false
$('#showme').fadeOut();
}
});
Check out an updated version of your fiddle here.
As an alternative, as another answer has also correctly pointed, you can use:
$('#showme').fadeOut(500, function() {
$(this).text(s).fadeIn(500);
});
Putting s inside text() can also check its status, because according to the documentation s is:
The text to set as the content of each matched element. When Number or Boolean is supplied, it will be converted to a String representation.
In your case, as I pointed above, the empty string is considered false, so it fulfils the requirement.
Note: In this case, $('#showme') will fade out anyway, but if the value is true (not empty) it will fade back in. I'm not sure if you actually want that particular effect, so take a look at this fiddle as well.
Set the fade in as a function of the fade out, this allows the text to fade out, change, then fade back in. The if statements aren't really necessary. I also corrected the usage of text().
$('#State').on('change', function() {
var s = $('#State option:selected').text();
$('#showme').fadeOut(300, function() {
$(this).text(s).fadeIn(300);
});
});
Fiddle update
Try the following:
var s = $('#State option:selected').text();

Check validation with id's and assign custom errors

(I am not using Jquery Validation)
I'm trying to return custom errors if the field is incorrect or empty. For instance, if the #id_first_name field is null. Append the string, " first name" to p#error to result in :
Please fill in your first name
I've made a fiddle here to show what I mean. So in the list of required fields... How would I be able to grab / check each individual required id and assign the corrosponding error?
Thank you for your help in advance!
You're fiddle should be as basic as possible, removing all other information, but you could try something like this,
$('form').on('submit',function(){
$('input').each(function(){
$this = $(this);
if($this.val() == 'null')
{
$('p#error').append('Please enter your ' + $this.attr('placeholder'));
}
}
});
You could do something like below
$('form input').on('blur', function() {
var id = $(this).attr('id');
var val = $(this).val();
if(id == 'myInput') {
if(!val.length) {
$('#error').append('Please enter a value into the input');
}
}
});
This is a simple way of doing form validation, just tailor the example to your needs.
EDIT
If you want it to work in your example it would be better to have a div with the id of error and append p tags with the corresponding error values.
Happy coding :)

jquery How to access only checked checkbox?

I have a div which contains 7 checkboxes , i wrote this following code for accessing only the checked checkbox into the array icons
var icons = $("div").find("input[type=checkbox]").each(function () {
if($(this).attr("checked") == "checked") return this; });
alert(icons.length);
but it always alert 7 .Can anybody tell me the problem?
var icons = $("div").find("input[type=checkbox]:checked");
the easiest way is to assign a class to target inputs and use checked selector, see an example below:
var icons = $('.box:checked');
Hiya demo http://jsfiddle.net/KzMqB/
You probably just need to check once using :checked and it will give you what you are looking for.
good read: http://api.jquery.com/checked-selector/
Hope this helps!
code
var icons = $("div").find("input[type=checkbox]:checked").each(function() {
alert("ID of checked checkbox = " + $(this).attr("id"));
});
You can use $.map,
$(document).ready(function() {
var checks = $.map($("div").find('input[type="checkbox"]:checked'),function(arr){
return arr;
})
console.log(checks.length);
})
or your method,
$(document).ready(function() {
var checks = $.each($("div").find('input[type="checkbox"]:checked'),function(){
return this;
})
console.log(checks.length);
})
var icons= $("div").find("input:checked").length;
alert(icons);

Toggle State Incorrect in jQuery

I am using jQuery to show / hide lists, but it takes two clicks on a link instead of just one to show the list. Any help?
jQuery.showList = function(object) {
object.toggle(function(){
object.html("▾");
object.siblings("ul.utlist").show("fast");
}, function(){
object.html("▸");
object.siblings("ul.utlist").hide("fast");
});
}
$(document).ready(function() {
$("#page").click(function (e){
e.preventDefault();
var target = $(e.target);
var class = target.attr("class");
if(class == "list")
$.showList(target);
});
});
It's probably because toggle thinks the object is already visible, and executes the 'hide' clause.
edit:
Eh.. quite circular logic; how else would a user be able to click on it :-)
PS. You changed the logic from is-object-visible? to is-list-visible? in your own reply.
Not sure if this will fix everything but stop using reserved keywords.
Change variable class to something like c. And Change object variable to at least obj.
Doing the following worked well
jQuery.showList = function(obj) {
var list = obj.siblings("ul.utlist");
if(list.is(":visible")){
obj.html("▸");
list.hide("fast");
} else {
obj.html("▾");
list.show("fast");
}
}

Categories