Using .after but only if the value does not exist - javascript

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

Related

Embed javascript function within another javascript function

I have a form with a conditional field that is only shown if the user selects a radio button for "other." If I remove the conditional on this field, my original javascript function works; however, with the conditional I can not get it to fire correctly.
The form has an event "cf.add" that fires when a conditional field is made visible, and using this jquery I get a correct response in the console:
jQuery( document ).on( 'cf.add', function(){
console.log('cf.add triggered' );
});
And if I remove the conditional so that this field is rendered when the page is rendered, I get the correct response in this field, which is to add a '$':
$("#fld_3169487_4").on("blur", handleChange);
function handleChange() {
var myValue = document.getElementById("fld_3169487_4").value;
if (myValue.indexOf("$") != 0)
{
myValue = "$" + myValue;
}
document.getElementById("fld_3169487_4").value = myValue;
}
I've tried putting this second function within the first, but no luck. I feel like I'm adding them in the incorrect order when I try to combine the two, I'm not sure what I'm doing wrong though.
I've also tried to call the function handleChange() on the 'cf.add' trigger, but that did not work for me either.
After some playing around, I figured it out:
jQuery( document ).on( 'cf.add', function(){
var otherField = $("#fld_3169487_3");
otherField.focus();
var dollarValue;
$(otherField).on("blur", function() {
dollarValue = otherField.val();
if (dollarValue.indexOf("$") != 0) {
dollarValue = "$ " + dollarValue;
}
$(otherField).val(dollarValue);
});
});
Since cf.add is an custom even that is published by your form, you can have other elements subscribe to the event:
$("#fld_3169487_4").on('cf.add', function(event){
if ($(this).val().indexOf("$") != 0)
{
$(this).val("$" + $(this).val());
}
});
Using $(this), we can target just the field the event is attached to. Additionally, data from the event publisher can be passed to the subscribers via the event argument.

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();

jquery: how to add event handler to dynamically added element without adding it to existing element again

I'll try to explain my problem:
I have a website where the user dynamically adds elements. They all belong to the "toBuy" class. Whenever a new element is added to this class I need to attach a click-handler to only this element but not to all others. To keep my code clean I want to have a function that does this work. Here is what i've tried:
this is how the stuff is added:
$("#addItemButton").click(function(){
var item= $('#item').val();
$('#item').val("");
var quantity= $('#quantity').val();
$('#quantity').val("");
var comment=$('#addComment').val();
$('#addComment').val("");
//construct new html
var newitem="<div class='toBuyItem'><div class='item'>";
newitem+=item;
newitem+="</div><div class='quantity'>";
newitem+=quantity;
newitem+="</div><div class='comment'><img src='img/comment";
if(comment==""){
newitem+="_none"
}
newitem+=".png' alt='Comment'></div><div class='itemComment'>"
newitem+=comment;
newitem+="</div></div>";
$("#toBuyItems" ).prepend( newitem );
toggle("#addItemClicked");
initializeEventListeners();
});
then this is the initializeEventListeners function (which I also run when the page loads so that the existing elements have the event handlers already:
function initializeEventListeners(){
$(".toBuyItem").click(function(){
console.log($(this).html());
console.log($(this).has('.itemComment').length);
if($(this).has('.itemComment').length != 0){
console.log("toggling");
$(this).addClass("toggling");
toggle(".toggling .itemComment");
$(this).removeClass("toggling");
}
});
}
function toggle(item){
$( item ).slideToggle(500);
}
now apparently what happens is that when a new element is added the existing elements get a new event handler for clicking (so they have it twice). Meaning that they toggle on and off with just one click. Probably it's damn simple but I cannot wrap my head around it....
EDIT:
so this works:
$(document).on('click', '.toBuyItem', function(){
if($(this).has('.itemComment').length != 0){
console.log("toggling");
$(this).addClass("toggling");
toggle(".toggling .itemComment");
$(this).removeClass("toggling");
}
});
Use jquery's on method. This way you have to add event only once. This will be added automatically to dynamically added elements.
$(document/parentSelector).on('click', '.toBuyItem', function() {
// Event handler code here
});
If you are using parentSelector in the above syntax, it has to be present at the time of adding event.
Docs: https://api.jquery.com/on
You can use jQuery.on method. It can attach handlers to all existing in the DOM and created in future tags of the selector. Syntax is as follows:
$(document).on('click', '.toBuyItem', function(){
//do onClick stuff
})
As others have suggested, you can delegate click handling to document or some suitable container element, and that's probably what I would do.
But you could alternatively define a named click handler, which would be available to be attached to elements already present on page load, and (scope permitting) to elements added later.
You might choose to write ...
function buy() {
if($(this).has('.itemComment').length != 0) {
$(this).addClass("toggling");
toggle(".toggling .itemComment");
$(this).removeClass("toggling");
}
}
function initializeEventListeners() {
$(".toBuyItem").on('click', buy);
}
$("#addItemButton").on('click', function() {
var item = $('#item').val(),
quantity = $('#quantity').val(),
comment = $('#addComment').val();
$('#item', '#quantity', '#addComment').val("");
//construct and append a new item
var $newitem = $('<div class="toBuyItem"><div class="item">' + item + '</div><div class="quantity">' + quantity + '</div><div class="comment"><img alt="Comment"></div><div class="itemComment">' + comment + '</div></div>').prependTo("#toBuyItems").on('click', buy);// <<<<< here, you benefit from having named the click handler
$newitem.find(".comment img").attr('src', comment ? 'img/comment.png' : 'img/comment_none.png');
toggle("#addItemClicked");
});

Jquery change color condition

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");
});
}
});

How do I empty an input value with jQuery?

I’m trying to make a modal dialog with images where you can select multiple images. I need to get values from an input and then to empty it, but I cannot empty the input. I tried .val('') and .val(null), but neither worked for me.
Here is the full code:
$("#hdselect").click(function(){
$(".modal").html("");
$.post('mediaservice.php',{hd:'ok',images:$("#hdimages").val()},function(data){
$(".modal").append(data);
});
$(".modal").dialog({
'modal':true,
'title':"Click the image to select",
'width':960,
'height':600,
'resizable':false,
'show': {effect: 'drop', direction: "up"},
'buttons': {"Ok": function() {
var hd=Array();
var hdval=$("#hdimages").val();
$("#hdimages").attr('value',' ');
$("input[name='hd[]']:checked").each(function(){
hd.push($(this).val());
});
if(hdval!=''){
hdval=hdval+","+hd;
}else{
hdval=hd;
}
$("#hdimages").val(hdval);
var images=$("#hdimages").val();
$.post('mediaservice.php',{getHd:images},function(data){
$("#imgthumbBase").append(data);
});
$(this).dialog("close");
}
}
});
});
The idea is that the user clicks a button and a modal dialog opens with multiple images and checkboxes. At this point I need to get the values from an input, and then clear it.
To make values empty you can do the following:
$("#element").val('');
To get the selected value you can do:
var value = $("#element").val();
Where #element is the id of the element you wish to select.
You could try:
$('input.class').removeAttr('value');
$('#inputID').removeAttr('value');
A better way is:
$("#element").val(null);
Usual way to empty textbox using jquery is:
$('#txtInput').val('');
If above code is not working than please check that you are able to
get the input element.
console.log($('#txtInput')); // should return element in the console.
If still facing the same problem, please post your code.
Another way is:
$('#element').attr('value', '');
$('.reset').on('click',function(){
$('#upload input, #upload select').each(
function(index){
var input = $(this);
if(input.attr('type')=='text'){
document.getElementById(input.attr('id')).value = null;
}else if(input.attr('type')=='checkbox'){
document.getElementById(input.attr('id')).checked = false;
}else if(input.attr('type')=='radio'){
document.getElementById(input.attr('id')).checked = false;
}else{
document.getElementById(input.attr('id')).value = '';
//alert('Type: ' + input.attr('type') + ' -Name: ' + input.attr('name') + ' -Value: ' + input.val());
}
}
);
});
For me this was the best way to solve this:
$('yourElementName').val(null);

Categories