Multiple condition in .each jQuery - javascript

Here is my HTML
<span class="sp-right">
<label>Name:</label>
</span>
<span class="sp-left">
<select name="omoor" required>
<option value="" style="display:none">something</option>
</select>
</span>
I want to change sp-rightclass to sp-left class and sp-left to sp-right with toggle .
here is my jquery :
$(".sp-right").each(function(){
$(this).removeClass("sp-right").addClass("sp-left");
});
it's working only once and for 1 element ?
Any idea ?
Thanks

As simple as one line with toggleClass:
$('.sp-right, .sp-left').toggleClass("sp-right sp-left");
No need to check for classes and remove/addClass manually, as toggleClass does exactly this. You can also provide multiple space separated classes to toggle.

Check the current classname inside the function.
$(".sp-left, .sp-right").each(function(){
var el = $(this);
if (el.hasClass('sp-left')) {
el.removeClass("sp-left").addClass("sp-right");
} else {
el.removeClass("sp-right").addClass("sp-left");
}
});

Related

Sidr - remove prefix from all the children classes using jQuery

I need to remove the prefix 'sidr-class-' from all the classes inside the 'sidr-inner' parent div. Sidr provides an option to remove all the prefixes, but it removes prefixes from ID's as well. I want to remove only the class prefixes. The HTML is as follows:
<div class="sidr-inner">
<div class="sidr-class-col-sm-12">
<h2>Search by location</h2>
<form>
<input type="search" class="sidr-class-form-control" placeholder="Your location / postal code">
<button type="submit" class="sidr-class-btn sidr-class-btn-default">Search</button>
</form>
</div>
</div>
At the moment I'm using the following jQuery snippet to search and add classes, but it's not convenient to do it with a large number of classes.
$(document).ready(function(){
if($('div').hasClass('sidr-class-col-sm-12')) {
$('.sidr-class-col-sm-12').addClass('col-sm-12');
}
});
Anyone have an idea how to get this done using jQuery or Javascript? Thanks in advance!
you can try this code:
$(document).ready(function(){
$('.sidr-inner [class*="sidr-class"]').each(function(){
var old_classes = $(this).attr('class');
old_classes = old_classes.replace(/sidr-class-/g, '');
$(this).attr('class', old_classes);
});
});
or this code:
$(document).ready(function(){
$('.sidr-inner [class*="sidr-class"]').each(function(){
$(this).attr('class', change_class);
});
});
function change_class(i, v)
{
return v.replace(/sidr-class-/g, '');
}
to solve your problem.

create multiple next and previous button in jquery on single page with same class

I am new in JavaScript and Jquery and I am facing problem while creating a code for multiple drop-down with next and previous option , but I don't want to write twice same code for next and previous. I just wanted to use same code dynamically. I have tried but did not got any answer. Plzz suggest ....
<div class="filter-category">
<div class="floor-dropdown">
<span class="prev">Prev</span>
<select class="roof-filter">
<option value="1" selected>All types</option>
<option value="2">Type1</option>
<option value="3">Type 2</option>
</select>
<span class="next">Next</span>
</div>
<div class="floor-dropdown">
<span class="prev">Prev</span>
<select class="roof-filter">
<option>011</option>
<option>222</option>
<option>333</option>
<option>444</option>
</select>
<span class="next">Next</span>
</div>
</div>
jQuery(".roof-prev").click(function () {
jQuery('.roof-filter option:selected').prev().attr('selected', 'selected');
});
jQuery(".roof-next").click(function () {
jQuery('.roof-filter option:selected').next().attr('selected', 'selected');
});
Please don't write this code with different class name for second one, I want to use this code without writing again.
Thanks in advance.
You can use this as a reference to the element which was clicked. From that you can find the select it relates to by finding the closest common parent. Try this:
jQuery(function($) {
$(".prev").click(function () {
$(this).closest('.floor-dropdown').find('option:selected').prev().attr('selected', 'selected');
});
$(".next").click(function () {
$(this).closest('.floor-dropdown').find('option:selected').next().attr('selected', 'selected');
});
});
Example fiddle

Jquery dynamic creating HTML divs on click

I’m looking for some direction for my problem.
I’ve HTML divs and I want to replicate it when user clicks on span with id plus-1.
This is my html
<div id = “tab”>
<div class="row">
<div>
<select id="ProjectsFolder0FolderId" name="data[ProjectsFolder][0][folder_id]">
<option value="1">Project Presentation</option>
<option selected="selected" value="4">Project Root</option>
</select>
</div>
<div>
<div>
<input type="text" required="required" id="ProjectsFolder0Linux" value="xyz" name="data[ProjectsFolder][0][linux]">
</div>
</div>
<div id="plus-1" >
<span>
Click here
</span>
</div>
</div>
</div>
Jquery
$(document).on('click', '#plus-1' , function() {
var html = "<div class=\"row\" >"
???
+ "</div>";
$('#tab').append(html);
});
It is appending above html defined in jquery , but I don’t know how to append entire HTML efficiently as required above on each click.
Demo FIDDLE
Jquery
$(document).on('click', '#plus-1' , function() {
var html = $(this).parent().clone();
html.find('#plus-1').attr('id','plus-'+($('#tab').find('.row').length+1));
$('#tab').append(html);
});
Made a jsfiddle for you - http://jsfiddle.net/23GCn/. You also have an error in your html, you need to use correct parenthesis on <div id="tab">
jQuery(function($){
var count = 1;
$(document).on("click", "[id^='plus']", function(){
newBlock = $(this).parents(".row").clone();
count += 1;
// change id of Plus button
newBlock.find("[id^='plus']").attr("id", "plus-"+count);
// Change id and name of select box
newBlock.find("select")
.attr("id", "ProjectsFolder"+count+"FolderId")
.attr("name", "data[ProjectsFolder]["+count+"][folder_id]");
// Same for input
newBlock.find("input[type='text']")
.attr("id", "ProjectsFolder"+count+"Linux")
.attr("name", "data[ProjectsFolder]["+count+"][linux]");
// append new element to your tab
$("#tab").append(newBlock);
});
});
Note that [id^='plus'] type selectors are very inefficient, means, slow. Consider using classes instead of ids, this way you avoid all of the code required to change ids, since you can't have elements with same id on your page obviously.

Select First Element by jQuery

This is My HTML Dom
<dd>
<div class="Addable Files">
<div style="margin:5px;">
<select name="Kind" id="kind">
<option value="1" >K1</option>
<option value="2" >K2</option>
<option value="3" >K3</option>
</select>
<div class="customfile">
<span aria-hidden="true" class="customfile-button button">Browse</span>
<input type="file" name="Files" class="fileupload customfile-input">
</div>
<select name="yap">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</div>
</div>
<input type="button" value="new" style="margin-top:5px;" class="AddNewE button red" id="AddFiles">
</dd>
And my Script:
//Add new Addable div
$('.AddNewE').click(function () {
var Target = $('.Addable.Files:first');
var CloneTarget = $(Target).clone();
CloneTarget.insertAfter('.Addable.Files:last');
$(Target).find('select').each(function () {
$(this).css('color', 'red');
});
});
So I expect when I click add button just first two select (two select of first div) be Red and all other selects don't changed, but I see weird behavior, In first Add everything is OK, but then in each Add all selects be red except second one, I think Target is first div and also I select Target's Select elements so why all selects be Red? where is my problem?
EDIT
I am sorry about wrong script, but this is my actual script:
//Add new Addable div
$('.AddNewE').click(function () {
var Target = $('.Addable.Files:first');
var CloneTarget = $(Target).clone();
CloneTarget.insertAfter('.Addable.Files:last');
$(CloneTarget).css('color', 'green');
$(Target).find('select').each(function () {
$(this).css('color', 'red');
});
});
This is achievable just by changing your function slightly. Try:
$('.AddNewE').click(function () {
var Target = $('.Addable.Files');
var CloneTarget = $(Target).first().clone();
CloneTarget.insertAfter('.Addable.Files:last');
$('select').css('color', 'gray');
$(Target).find('select').each(function () {
$(this).css('color', 'red');
});
});​
To summarise the points I have changed, I have edited your Target variable to target all of the .Files items, then changed the CloneTarget to only clone the first .Files target. That way, when it comes to changing them all to red you're actually changing all the existing .Files items except the new one you're adding.
Demo: http://jsfiddle.net/usZPN/
Your select is on .Addable.Files:first which selects the first select with that name, didn't you want to select the first div underneath like so: .Addable.Files > div:first-child?
I guess the following fiddle solves your purpose.
http://jsfiddle.net/meetravi/9ehAF/
I am finding a bug in the code you have written in the following line.
$('.select').css('color', 'gray');
There is no select class in your code rather the code should be
$('select').css('color', 'gray');
Worksforme in http://jsfiddle.net/Y2XhV/, although I'm not sure which <div> you want to clone: the one with the margin or the one with the 2 classes? Your selectors are for the latter case. Yet, there are some small improvements to your code making it simpler:
//Add new Addable div
$('.AddNewE').click(function () {
var $Target = $('.Addable.Files:first');
var $CloneTarget = $Target.clone();
$CloneTarget.insertAfter('.Addable.Files:last');
$Target.find('select').css('color', 'red');
});
You don't need to recreate new jQuery objects from Target when you already have one, and .css() doesn't need a each.

input:radio click function isn't triggering in IE / Firefox

I have a form with multiple inputs / radio buttons.
I also have a series of Yes & No radio buttons. When the "Yes" radio button is checked, I have some data slide down beneath.
HTML:
<div class="item seperator first clearfix">
<label>test</label>
<div class="radioWrap">
<label class="yes">
<input class="homepageContent" name="homepageContent" type="radio" value="yes" />
</label>
<label class="no">
<input class="homepageContent" name="homepageContent" type="radio" value="no" checked />
</label>
</div>
</div>
<div class="extrasInner">
<div class="item clearfix">
<label for="theContent">Your Content:</label>
<textarea id="theContent" name="theContent"></textarea>
</div>
</div>
<div class="extrasOuter hide clearfix">
Make Changes
<span>Click "Make Changes" to update.</span>
</div>
The jQuery:
$("input:radio[name=homepageContent], input:radio[name=addSocialIcons], input:radio[name=addTracking]").click(function() {
var value = $(this).val();
if (value == 'yes') {
$(this).parent().parent().parent().next().slideDown();
$(this).parent().parent().parent().next().next().slideDown();
} else {
$(this).parent().parent().parent().next().slideUp();
$(this).parent().parent().parent().next().next().slideUp();
}
});
Question 1) This works absolutely fine in Google Chrome, but not in Firefox and IE. It doesn't seem to recognise the click function?
Solved: I had a function within one of my files that removes the value from input fields on focus and this was stripping the value of the radio buttons as well in IE / Firefox (but not chrome!).
Question 2) Is my DOM traversing for the slideUp / slideDown an acceptable way of achieving what I'm trying to do? Are there any disadvantages to how I'm doing it and can it be improved?
Answer to #1
As Anthony Grist pointed out, there doesn't seem to be an issue with the click function.
Answer to #2
Your DOM traversal seem a bit unnecessary. In fact, your DOM structure is in need of rearrangement.
Using a checkbox instead of radio buttons. A checkbox only accepts two values: true or false, or in your case, yes or no. It seems more suitable.
Encapsulate your extras inner and extras outer divs inside your item div instead of having it next to the checkbox. This way, you make it easier to traverse within the item.
Also, you should read up on the different types of traverse functions JQuery has:
.parent() / .parents()
.children()
.closest()
.next()
.prev()
.siblings()
.find()
and many more.
Knowing all of these traverse functions, you'll most likely never ever do parent().parent().parent()... again. :)
Here's a JSFiddle example | Code
HTML
<ul>
<li class='item'>
<label>
<input class="homepageContent" name="homepageContent" type="checkbox" value="yes" />
Item 1
</label>
<div class='extras'>
<div class='inner'>
<label>
Your Content:<textarea name="content"></textarea>
</label>
</div>
<div class='outer'>
Make Changes
<span>Click "Make Changes" to update.</span>
</div>
</div>
</li>
</ul>
Javascript
$("input:checkbox").click(function() {
var $this = $(this),
$item = $(this).closest(".item");
if($this.is(':checked')){
$(".extras", $item).slideDown();
}else{
$(".extras", $item).slideUp();
}
});
CSS
.extras{
display: none;
}
Value of the radio button will always be same, no matter it is checked or not. If you want to know the particular radio button is checked or not then use this code. Based on the status of the radio button do your stuff.
var value = $(this).attr('checked')
That is working for me in FF (jsfiddle), although the DOM looks a little convoluted (I'm guessing because it's missing a lot of your other CSS/resources).
I think you can simplify the jQuery selectors a lot. Generally, using simple ID or class selectors will make the your page much more performant (and simpler!)
$('.homepageContent').click(function() {
var value = $(this).val();
if (value == 'yes') {
$('.extrasInner').slideDown();
$('.extrasOuter').slideDown();
} else {
$('.extrasInner').slideUp();
$('.extrasOuter').slideUp();
}
});
Hopefully doing something like this makes it work cross browser better too.
try this way
$("input:radio[name=homepageContent], input:radio[name=addSocialIcons], input:radio[name=addTracking]").click(function() {
var value = $(this).val();
if (value == 'yes') {
$(this).parents('.seperator').next().slideDown();
$(this).parents('.seperator').next().next().slideDown();
} else {
$(this).parents('.seperator').next().slideUp();
$(this).parents('.seperator').next().next().slideUp();
}
});
EDIT
​
and also a point
wrap your code inside
$(document).ready(function(){});
like this
$(document).ready(function(){
$("input:radio[name=homepageContent], input:radio[name=addSocialIcons], input:radio[name=addTracking]").click(function() {
var value = $(this).val();
if (value == 'yes') {
$(this).parents('.seperator').next().slideDown();
$(this).parents('.seperator').next().next().slideDown();
} else {
$(this).parents('.seperator').next().slideUp();
$(this).parents('.seperator').next().next().slideUp();
}
});
});

Categories

Resources