how can i find closest span? - javascript

let's say i am having fallowing html structure-
<div data-theme="a" class="ui-btn ui-btn-icon-right ui-btn-corner-all ui-shadow ui-btn-up-a">
<span class="ui-btn-inner ui-btn-corner-all">
<span class="ui-btn-text">Select One</span>
<span class="ui-icon ui-icon-arrow-d ui-icon-shadow">
</span>
</span>
<select onchange="selectState(this,'ADDR_SHIP_STATE')" id="ADDR_SHIP_STATE" name="ADDR_SHIP_STATE">
<option>Hi</option>
<option>Hello</option>
<option>How</option>
<option>are</option>
<option>you</option>
</select>
</div>
what i am trying to do is on change of select box, take the text of selected option and place it inside span(replace select one with this data) having class name ui-btn-text
below is the code which i ahve tried so for without any luck
function selectState(id,stateId){
var selectedState = $("#"+stateId+" option:selected").text();
$(id).closest("ui-btn-text").text(selectedState);
}
Please suggest me how can i do this..

.closest()ref will progress up the DOM but won't get down like .parents() does (btw, you didn't add the . (dot) for the class search but this is probably a typo)
Here is a try:
$(id).parent().find(".ui-btn-text").text(selectedState);

Try -
function selectState(id, stateId) {
var selectedState = $("#" + stateId + " option:selected").val();
$(id).parents('div').find(".ui-btn-text").text(selectedState);
}
This will -
Find the parent 'div' of the 'select' element
Use find to get the .ui-btn-text element contained in the parent div
Demo - http://jsfiddle.net/H2pea/1

Using attributes like onchange is not really unobtrusive way if you use jQuery. This is better:
$('#ADDR_SHIP_STATE').change(function() {
$(this).prev().find('.ui-btn-text').text($(this).val());
});

Related

Selecting element with JS issue

Please help me to understand this. I have HTML code like this:
<div id="one">
<div>
<div>
<span class="spanone"></span>
<span class="spantwo"></span>
<div>
</div>
</div>
.
.(some other html of the page)
.
<sometag class="spanone"></sometag>
<someothertag class="spantwo"></someothertag>
And I basically want to target only the first <span> and the second by JS without touching the sometags elements. In other words the: <span class="spanone"> and <span class="spantwo">. And then I want to use innerHTML to replace the code with the one I want.
Thanks!
var spanone = document.querySelector('.span1');
var spantwo = document.querySelecftor('.span2');
spanone.innerHTML = "Replacement";
spantwo.innerHTML = "Replacement";
You can achieve this in a couple ways
Use id
<span class="spanone" id="myspan1"></span>
<span class="spantwo" id="myspan2"></span>
so in vanilla JS
var d = document;
d.getElementById('myspan1');
d.getElementById('myspan2');
or with classes
<span class="spanone myspans"></span>
<span class="spantwo myspans"></span>
and in your JS
d.querySelectorAll('.myspans')
This should work:
var spanone = document.querySelector('.spanone')[0];
var spantwo = document.querySelecftor('.spantwo')[0];

jQuery show and hide dynamic classes not working

I am trying to hide and show div's displayed on my page with a select element however having a bit of trouble as I can't seem to get the jQuery to function.
I am listing results from my SQL table using PHP that currently displays every row onto my page and prints them into a list.
I want to make the jQuery hide the div's that don't have a class that matches the select option that is selected.
Here is an example of the listing template that echo's out all of the MySQL results and displays them into a template and is then looped to display every row on the table:
<?php while($row = $results->fetch(PDO::FETCH_ASSOC))
{
echo '
<div class="listing-container ' . $row["Make"] . '">
<h3 class="model-listing-title clearfix">'.$row["Make"].' '.$row["Model"].' '.$row["Variant"].'</h3>
<h3 class="price-listing">£'.number_format($row['Price']).'</h3>
</div>
<div class="listing-container-spec">
<img src="'.(explode(',', $row["PictureRefs"])[0]).'" class="stock-img-finder"/>
<div class="ul-listing-container">
<ul class="overwrite-btstrp-ul">
<li class="diesel-svg list-svg">'.$row["FuelType"].'</li>
<li class="saloon-svg list-svg">'.$row["Bodytype"].'</li>
<li class="gear-svg list-svg">'.$row["Transmission"].'</li>
<li class="color-svg list-svg">'.$row["Colour"].'</li>
</ul>
</div>
<ul class="overwrite-btstrp-ul other-specs-ul h4-style">
<li>Mileage: '.number_format($row["Mileage"]).'</li>
<li>Engine size: '.$row["EngineSize"].'cc</li>
</ul>
<button href="#" class="btn h4-style checked-btn hover-listing-btn"><span class="glyphicon glyphicon-ok"></span> History checked
</button>
<button href="#" class="btn h4-style more-details-btn hover-listing-btn tst-mre-btn"><span class="glyphicon glyphicon-list"></span> More details
</button>
<button href="#" class="btn h4-style test-drive-btn hover-listing-btn tst-mre-btn"><span class="test-drive-glyph"></span> Test drive
</button>
<h4 class="h4-style listing-photos-count"><span class="glyphicon glyphicon-camera"></span> 5 More photos</h4>
</div>
';
} ?>
The 'Make' is added to the listing-container div to add a class to be able to filter the results with jQuery.
Here is the form with the select element I am using:
<form>
<select class="form-control select-box">
<option value="make-any">Make (Any)</option>
<?php while($make = $filterres->fetch(PDO::FETCH_ASSOC))
{
echo '
<option>'.$make["Make"].'</option>
';
} ?>
</select>
<select class="form-control last-select select-box">
<option value="model-any">Model (Any)</option>
<option value="two">Two</option>
<option value="three">Three</option>
<option value="four">Four</option>
<option value="five">Five</option>
</select>
</form>
As you can see the select option contains the 'Make' and is looped.
So down to the jQuery:
<script>//Wait for DOM to load
(function() {
$(“.select-box”).change( function() {
// get the value of the select element
var make = $(this).val();
//get all of the listing-container divs, remove the ones with the selected make class, then hide the rest
$(“.listing-container”).not(“.” + make).hide();
});
});</script>
So in theory this should work but for some reason it isn't, can anybody notice anything that might be wrong?
I have placed my script below the core jQuery in my footer and it still doesn't work.
Here is a live example: http://www.drivencarsales.co.uk/used-cars.php
Looks like you're using the wrong quotes in the source code of that page try replacing them with "
//Wait for DOM to load
$(function() {
$(".select-box").change( function() {
// get the value of the select element
var make = $(this).val();
//get all of the listing-container divs, remove the ones with the selected make class, then hide the rest
$(".listing-container").not("." + make).hide().next().hide();
});
});
Edit
You also need a $ before the function
If I understand you correctly ↓ working code ↓
$(function() {
$('.select-box').on("change",function() {
var make = this.value;
$('div.listing-container.'+make+",div.listing-container."+make+" + div.listing-container-spec").show();
$('div.listing-container:not(.'+make+'),div.listing-container:not(.'+make+') + div.listing-container-spec').hide();
});
});
And shorter code (but slower):
$(function() {
$('.select-box').on("change",function() {
var make = this.value;
$('.listing-container.'+make+",.listing-container."+make+" + div").show();
$('.listing-container:not(.'+make+'),.listing-container:not(.'+make+') + div').hide();
});
});
P.S.You miss value attribute (but in live example everything ok):
echo '<option value="'.$make["Make"].'">'.$make["Make"].'</option>';

I need help on jquery/javascript

Ok, so, I have a question.
I am getting the element ID like this.
<td id="ctl00_cphRoblox_lstItemsForResale_ctrl1_Td1" class="PriceBuyContainer">
document.getElementById("ctl00_cphRoblox_lstItemsForResale_ctrl1_Td1")
And this is below it.
<div class=" roblox-buy-now btn-primary btn-small PurchaseButton " data-item-id="168167114" data-item-name="Wanwood Visor" data-userasset-id="1941846042" data-product-id="20655974" data-expected-price="114" data-asset-type="Hat" data-expected-currency="1" data-expected-seller-id="6141596" data-bc-requirement="0" data-seller-name="laughableblox">
Buy Now
<span class="btn-text">Buy Now</span>
</div>
How would I get data-expected-price="NUMBERHERE" by using?
document.getElementById("ctl00_cphRoblox_lstItemsForResale_ctrl1_Td1")`
Use JQuery's .data() function. First you can grab the td element via jQuery:
var el = $("#ctl00_cphRoblox_lstItemsForResale_ctrl1_Td1");
Then find it's first child element and use use .data() to return the expected-price data attribute's value:
alert(el.find('> div').data('expected-price'));
jsFiddle

how to change values in a hidden chunk of html code

I have this hidden block of code that i want to call based on the values that are received from server:
<div id="hiddenChart" style="display:none;">
<li style="height:auto;">
<div class="col-sm-4" id="chart_0_0">
<div class="panel panel-success" style="width:550px; height:auto;" id="accordion_0_0">
<div class="panel-heading">
<div class="btn-group" style="float:right;">
<i class="glyphicon glyphicon-minus" id="minimize_0_0"></i>
<i class="glyphicon glyphicon-remove" id="close_0_0"></i>
</div>
<h3 class="panel-title">title</h3>
</div>
<div class="panel-body" style="height:400px;">
<nvd3-multi-bar-chart data="Sec1Graf1Data" id="dataChart_0_0" height="400" showXAxis="true" reduceXTicks="true" showYAxis="true" showLegend="true" showControls="true" tooltips="true">
<svg></svg>
</nvd3-multi-bar-chart>
</div>
</div>
</div>
</li>
</div>
but i need to change some values: ids, tags, data variables.
I know how to show the code using "$('ul').append($('div').html());" but i have to change it before doing it.
How can i do it?
How do i define in which fields i have to insert the string i'me receiving?
Thk
UPDATE:
I was able put it to work, here is the fiddle with it fiddle.
When i inspect the element, the ids that i want to change, instead of #1, it returns chart_0_0.
Thank you all for your posts and help
You can get a reference to your div like this:
var $div = $('#hiddenChart');
To clone it,
var $clonedDiv = $div.clone();
Then, in the $cloneDiv object, you make the changes:
$clonedDiv.find(--selector of a node--).attr(atributeName, atributeValue); //change/add attribute
$clonedDiv.find(--selector of a node--).removeAttr(atributeName); //remove attribute
And so on. I won't explain how jQuery works, Lekhnath gave you a link.
Finally you insert the $clonedDiv with .appendTo() wherever you want. The original div remains untouched so you can clone it again and again.
Jquery Change text/html from a hidden div content :
Simple
maintain a copy of the hidden content
replace the content based on the element class/id selector with the server response
then paste the html into another div
replace the content of the hidden back to original (optional)
http://jsfiddle.net/austinnoronha/ZJ3Nt/
$(document).ready(function(){
var serverRes = {
title: "New Title In Header",
body: "New body text from server <\/br><nvd3-multi-bar-chart data=\"Sec1Graf1Data\" id=\"dataChart_0_0\" height=\"400\" showXAxis=\"true\" reduceXTicks=\"true\" showYAxis=\"true\" showLegend=\"true\" showControls=\"true\" tooltips=\"true\"><svg><\/svg><\/nvd3-multi-bar-chart>"
};
var tmpOldCont = $("#hiddenChart").html();
var counter = 1;
$(".serverres").click(function(){
$("#hiddenChart").find(".panel-body").html(counter + " = " + serverRes.body);
$("#hiddenChart").find(".panel-title").text(serverRes.title + " " + counter);
counter++;
$(".box-container").html($("#hiddenChart").html());
$("#hiddenChart").html(tmpOldCont);
});
});

Getting value from input control using jQuery

I am using the teleriks treeview control (asp.net mvc extensions), where I may have up to three children nodes, like so (drumroll...... awesome diagram below):
it has its own formatting, looking a bit like this:
<%=
Html.Telerik().TreeView()
.Name("TreeView")
.BindTo(Model, mappings =>
{
mappings.For<Node1>(binding => binding
.ItemDataBound((item, Node1) =>
{
item.Text = Node1.Property1;
item.Value = Node1.ID.ToString();
})
.Children(Node1 => Node1.AssocProperty));
mappings.For<Node2>(binding => binding
.ItemDataBound((item, Node2) =>
{
item.Text = Node2.Property1;
item.Value = Node2.ID.ToString();
})
.Children(Node2 => Node2.AssocProperty));
mappings.For<Node3>(binding => binding
.ItemDataBound((item, Node3) =>
{
item.Text = Node3.Property1;
item.Value = Node3.ID.ToString();
}));
})
%>
which causes it to render like this. I find it unsual that when I set the value it is rendered in a hidden input ? But anyway:...
<li class="t-item">
<div class="t-mid">
<span class="t-icon t-plus"></span>
<span class="t-in">Node 1</span>
<input class="t-input" name="itemValue" type="hidden" value="6" /></div>
<ul class="t-group" style="display:none">
<li class="t-item t-last">
<div class="t-top t-bot">
<span class="t-icon t-plus"></span>
<span class="t-in">Node 1.1</span>
<input class="t-input" name="itemValue" type="hidden" value="207" />
</div>
<ul class="t-group" style="display:none">
<li class="t-item">
<div class="t-top">
<span class="t-in">Node 1.1.1</span>
<input class="t-input" name="itemValue" type="hidden" value="1452" />
</div>
</li>
<li class="t-item t-last">
<div class="t-bot">
<span class="t-in">Node 1.1.2</span>
<input class="t-input" name="itemValue" type="hidden" value="1453" />
</div>
</li>
</ul>
</li>
</ul>
What I am doing is updating a div after the user clicks on a certain node. But when the user clicks on a node, I want to send the ID not the Node text property. Which means I have to get it out of the value in these type lines <input class="t-input" name="itemValue" type="hidden" value="1453" />, but it can be nested differently each time, so the existing code I ahve doesn't ALWAYS work:
<script type="text/javascript">
function TreeView_onSelect(e) {
//`this` is the DOM element of the treeview
var treeview = $(this).data('tTreeView');
var nodeElement = e.item;
var id = e.item.children[0].children[2].value;
...
</script>
So based on that, what is a better way to get the appropriate id each time with javascript/jquery?
edit:
Sorry to clarify a few things
1) Yes, I am handling clicks to the lis of the tree & want to find the value of the nested hidden input field. As you can see, from the telerik code, setting item.Value = Node2.ID.ToString(); caused it to render in a hidden input field.
I am responding to clicks anywhere in the tree, therefore I cannot use my existing code, which relied on a set relationship (it would work for first nodes (Node 1) not for anything nested below)
What I want is, whenever there is something like this, representing a node, which is then clicked:
<li class="t-item t-last">
<div class="t-bot">
<span class="t-in">Node 1.1.2</span>
<input class="t-input" name="itemValue" type="hidden" value="1453" />
</div>
</li>
I want the ID value out of the input, in this case 1453.
Hope this now makes a lot more sense.
if possible would love to extend this to also store in a variable how nested the element that is clicked is, i.e. if Node 1.1.2 is clicked return 2, Node 1.1 return 1 and node 1 returns 0
It's a little unclear what you're asking, but based on your snippet of JavaScript, I'm guessing that you're handling clicks to the lis of the tree & want to find the value of the nested hidden field? If so, you want something like this:
function TreeView_onSelect(e) {
var id = $(e.item).find(".t-input:first").val();
}
Edit: In answer to your follow-up question, you should be able to get the tree depth with the following:
var depth = $(e.item).parents(".t-item").length;
In jQuery you can return any form element value using .val();
$(this).val(); // would return value of the 'this' element.
I'm not sure why you are using the same hidden input field name "itemValue", but if you can give a little more clarity about what you are asking I'm sure it's not too difficult.
$('.t-input').live('change',function(){
var ID_in_question=$(this).val();
});

Categories

Resources