Select First Element by jQuery - javascript

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.

Related

change background of next div depending on selected item

EDIT : It seems like I didn't make myself clear, sorry about that, so I update the code.
I have many "select", with different IDs and same class:
<div class="objvalide">
<select id="obj1-1" class="swit">
<option selected="selected" value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<div class="switchy-container">
<div class="switchy-bar">
<div class="switchy-slider" draggable="true" style="left: 0px;"></div>
</div>
</div>
</div>
<div class="objvalide">
<select id="obj1-2" class="swit">
<option selected="selected" value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<div class="switchy-container">
<div class="switchy-bar">
<div class="switchy-slider" draggable="true" style="left: 0px;"></div>
</div>
</div>
</div>
... and more ...
Here's the JS I have so far:
$(function() {
$('.swit').switchy();
$('.swit').change(function() {
var select = $(this);
var id = select.attr('id'); //alert(id); <- Works fine, I get the correct ID
/* what do I hav to do here in order to have .switchy-bar bg change color only for this particular .objvalide > .switchy-container > .switchy-bar ? */
});
});
At the beginning, all options are "0".
Each and every .switchy-bar background is white.
When I select option value "1" in obj1-2 for instance, I need the background of its .switchy-bar to be red. If I select option value "2", background of its .switchy-bar has to be green.
The other select and background must remain untouched.
Thanks
$('.swit').on('change', function() {
var myVal = $(this).val();
switch (myVal){
case '1': $(this).siblings().children('.switchy-bar').css('background', '#000');
break
case '2': $(this).siblings().children('.switchy-bar').css('background', '#f00');
break
default: $(this).siblings().children('.switchy-bar').css('background', '#fff');
}
})
http://codepen.io/gmrash/pen/LpoGYG?editors=101
select[0].style.backgroundColor=bgColor
If you want to change the background of selected option,
var a= select[0].selectedIndex;
select[0][a].style.backgroundColor=bgColor
Use the click event to fire a function that makes the necessary changes. Use the this selector to ensure your changes only happen on the element that triggered the function.
If you want to make the changes happen to the parent/child (parent in your case) element of the triggering element, you can always traverse the DOM relative to this using JQuery methods this.parent()/this.children(). For instance, if you want to change the background-color of a <select> element based on the clicked <option>, you can do that in the following way using JQuery:
var backgroundcolor = ["red", "green", "white"];
$('option').click(function() {
$(this).parent().css("background-color", backgroundcolor[$(this).val()]);
});
Here, the array is created in order with the colors corresponding to each option.
Please use addClass("color-1") and removeClass("color-1"). That is the only solution for this and do what do want in that class.
Sol-1 (Without animate background)
In css
.color-1{
//Do stuff
}
This will Help You.
Also
Sol-2 (With animate background)
var record= $(this).find('switchy-bar');
record.animate(
{backgroundColor: '#FFF'},
{duration: 'fast', complete: function() {
//Here You can animate with new color. and old animation will be overwritten
record.css('backgroundColor', '');
}}
);

Show a div on option selection

I have a selection menu (drop down list).
<select>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
& the following div which located in somewhere in my page.
<div id="somediv">This is a string.</div>
I want to display the above div upon selecting the second item of the menu (id="two").
I have 2 questions: (1) What is the best way to keep this div hidden by default? I will just add display:none; to its styling, but maybe there is a better solution? (2) How can I make the div show up when the option of id="two" is selected? Any answer would be greatly appreciated.
So I wrote a simple jquery script that does what you described. Let me know if it fixes your problem. You can also do this with javascript, but I think jquery works for this just fine.
http://codepen.io/Francisco104/pen/vEPRgp
$('select').change(function(){
decide($(this));
});
var decide = function (elem) {
var touch = elem;
if (touch.val() === 'anything') {
return $('#somediv').css('display', 'block');
}
};
For hiding it by default, using style="display: none"is the easiest. You could do it using jquery $('div#somediv').hide(); but I don't see any benefit to that other than you possibly wanting to keep the show/hide logic together.
Here are two simple solutions using a change() event.
If div#somediv should be shown permanently when option#two has been selected:
$("select").change(function() {
if ($(this).val() == 'anything') $('div#somediv').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
<div id="somediv" style="display: none">This is a string.</div>
If div#somediv should be shown while option#two is selected and disappear if the user selects another option:
$("select").change(function() {
$('div#somediv').toggle($(this).val() == 'anything');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
<div id="somediv" style="display: none">This is a string.</div>
You should probably give an id to the select as well, to make the jQuery selector less brittle.
So, I'd have a class for the div, let's say, is-hidden and my CSS will have .is-hidden { display: none; }. Then, do the following.
HTML:
<div id="somediv" class="is-hidden">This is a string.</div>
JS:
$div = $("#somediv");
$("select").on("change", function() {
$div.is(".is-hidden") || $div.addClass("is-hidden");
//Option 1
if ($(this).find(":selected")[0].id === "two") {
$div.removeClass("is-hidden");
}
//Option 2 (same as above, but a bit shorter)
$(this).find(":selected")[0].id === "two" && $div.removeClass("is-hidden");
});
Here is what you can do:
in your html file:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<select>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
You'll need to import the JQuery library (which I show you there right above the <select> element) so that you can execute your script.
In your css file:
#somediv {
display: none;
}
and finally here is the script that will show the dive when "plane" is selected
$('select').change(function(){
$('#somediv').css('display','block');
});
Take a look at this JSFIDDLE I made for you.
1) You can hide the div initially giving the css property display:none; or by setting its display property using javascript which will run in initial load.
2) You can listen to the onchange event of the selectfield and check if value is 'anything' then show the div by changing its display style property to block and hidden in other cases.
document.getElementById("somediv").style.display='none';
var showHideDiv=function(selectField){
var divElement=document.getElementById("somediv");
if (selectField.value=='anything')
divElement.style.display='block';
else
divElement.style.display='none';
}
<select onchange='showHideDiv(this)'>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
<div id="somediv">This is a string.</div>
The simplest way to hide within HTML
<div hidden>content</div>
To display an hidden div
$(document).ready(function(){
$("select").change(function () {
$( "select option:selected").each(function(){
if($(this).attr("value")=="anything"){
$("#somediv").show();
}
});.
});
Display none works.
Have you tried keying into the onchange event? http://www.w3schools.com/jsref/event_onchange.asp?

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.

How get the class of the div on clicking the select option inside that div?

I have two divs which show the product details content inside them, something like this:
<div class="product-style-odd">
<select>
<option value="active" onClick="changeStatus(<?php echo $productid;?>,0)">Activate</option>
<option value="inactive" onClick="changeStatus(<?php echo $productid;?>,1)">Deactivate</option>
</select>
</div>
<div class="product-style-even">
<select>
<option value="active" onClick="changeStatus(<?php echo $productid;?>,0)">Activate</option>
<option value="inactive" onClick="changeStatus(<?php echo $productid;?>",1)>Deactivate</option>
</select>
</div>
<script>
function changeStatus(productid, status){
//Now what I want to reference and hide that div in which changeStatus function was invoked
}
</script>
Now little explanation of above code. Both of these odd and even style divs are inside a loop so they are repeated depending upon the number of iterations in the loop.
Now what I want to achieve is that when the user clicks on inactive option from select menu then that particular div should fadeOut and I change the status of that product via Ajax.
I don't know how to get class of that particular div which was clicked.
And sorry for poor indentation of the code, I am not much familiar with SO editor.
EDIT:
Problem is still not solved.
The reason is the structure of that page is very complex. First I have body and then a div and then several divs and then comes a div with class product-style-even or product-style-odd. Now if I put the code to select the parent div then it selects the div after body.
$('select').click(function(){
var divClass=$(this).parent('div').attr('class');
});
How about something like this?
$("select").change(function () {
var selectVal;
$("select option:selected").each(function () {
selectVal = $(this).val();
});
if (selectVal == 'inactive') {
var selectParentDiv = $(this).parents('div');
selectParentDiv.fadeOut();
console.log(selectParentDiv.attr('class'));
}
});
Example: http://jsfiddle.net/rjngr/3/
With jQuery:
$(this).parents('div:first').hide();
in body of function changeStatus(productid, status)

Issue displaying divs using show.hide?

Hi I have some javascript which works in a standalone web page with 5 divs, what it does is when an option is selected it will show a div and hide the others based on drop down selection.Basically what the code does is when a sector is selected on the drop down that corresponding DIV will be displayed eg pubs.
The problem I am having is in the web page I want this working on I have lots of Div tags and when the page loads all the Divs on the page are hidden, obviously I don't want this.
Any help would be much appreciated
The code that hides all the divs on page load is
$('div').not(name).hide();
Is there a way of solving this problem I cant see how I am going to get round it at the moment.?
JS
<script>
$(document).ready(function () {
function showTab( name )
{
name = '#' + name;
$('div').not(name).hide();
$(name).show();
}
$('#dropdown').change( function() {
showTab( $( this ).val() );
});
showTab( $('#dropdown').val() );
});
HTML
<form>
<p>
<select id="dropdown" name="dropdown">
<option value="Pub-Chains" selected="selected">Pubs </option>
<option value="Councils">Councils </option>
<option value="Property">Property </option>
<option value="Various">Various </option>
<option value="Universitys">Universitys </option>
</select>
</p>
</form>
My Div's are named like so
Div id="Pub-Chains"
Div id="Councils"
Div id="Property"
Div id="Various"
Div id="Universitys"
You have to group up the div you want to participate in show hide to separate them from other divs on the page. You can assign a common class to them and use that class to hide them.
Div id="Pub-Chains" class="opt"
Div id="Councils" class="opt"
Div id="Property" class="opt"
Div id="Various" class="opt"
Div id="Universitys" class="opt"
$('div.opt').hide();
$(document).ready(function () {
var ddl = $("#dropdown");
$('#' + ddl.val()).show().siblings().hide();
ddl.change(function () {
$('#' + $(this).val()).fadeIn().siblings().hide();
});
});
See demo
If your target <div>s are all siblings then you can easily do something like follows.
<div>
<div id="Pub-Chains">
<div id="Councils">
<div id="Property">
...
</div>
$(function(){
$("select#dropdown").change(function(){
$('#' + $(this).val()).show().siblings().hide();
}).change();
});
See it here.
If you have a more complicated layout then you can think of using classnames to group the <div> elements.
try this:
$(document).ready(function () {
function showTab( name ){
name = '#' + name;
$(name).siblings().hide(); //<-- hide this way
$(name).show();
}
and if this is not working then you can do this just put it outside of doc ready handler
function showTab( name ){
name = '#' + name;
$(name).siblings().hide(); //<-- hide this way
$(name).show();
}
$(document).ready(function () {
// then all your change stuff here
create a parent div to all this div... and call it in selector..
try this
<div id="tabdivs">
Div id="Pub-Chains"
Div id="Councils"
Div id="Property"
Div id="Various"
Div id="Universitys"
</div>
jquery
*updated*
$('#tabdivs').children().not(name).hide();
fiddle here..

Categories

Resources