How to get specific div through this? - javascript

I build a method that allow me to return the clicked element by the user, something like this:
$('#button2').on('mouseover', function()
{
console.log(this);
}
this return:
<tr id="res-7" class="entry border-bottom" rel="popover" data-original-title="" title="">
<td style="padding-left: 10px">
<div class="name"><strong>Test</strong></div>
<div class="description">Foo</div>
</td>
</tr>
essentially my target is get the content of div name and div description, someone could explain how to do this? Thanks.

Something like this: jsfiddle
$(document).on("mouseover","tr", function(){
var name = $(this).find(".name").text();
var description = $(this).find(".description").text();
console.log("Name: "+name+"\nDecsription: "+description);
})
Don't forget ID of each element must be unique so your code is not correct because "#button2" must be unique, so this is always #button2 in your function.
Note the difference between text() and html(). I used .text() to get just the text without "strong" code. If you need it use html().

You could use innerHTML
$(this).find('name').innerHTML; //returns "test"
$(this).find('description').innerHTML; //returns "foo"
This will find the class within the current element, and return the values you need.

Since you already have an id on your element, accessing the name and description attributes is easy:
$('#button2').on('mouseover', function() {
var $res7 = $('#res-7');
// Access the two divs
var name = $res7.find('.name').text(); // or .html()
var description = $res7.find('.description').text(); // or .html()
// Print them out
console.log(name);
console.log(description);
});
Of course, this block of code should be inside a jQuery ready event handler.

I'm sure there is a cleaner way, but this should get you what you want.
$('#button2').on('mouseover', function()
{
console.log($(this).find(".name").html());
console.log($(this).find(".description")).html());
}

Related

How to Get the Value Held Within a Custom Element in a <div>

Hopefully, this is fairly straight forward. From within JavaScript code, how do you get the value of 1 from the attribute dataID within the div element below:
<div class="widget" dataID="1"></div>
Thanks
You can get the attribute value like this:
var value = element.getAttribute('dataID');
Before that, you need to get the reference to the element. You can get it by adding id to the element:
var element = document.getElementById('element-id');
, or by class:
var elements = documents.getElementsByClassName('widget');
Array.from(elements).forEach(function(element) {
var value = element.getAttribute('dataID');
//...
};
Just read an attribute:
console.log(document.querySelector(".widget").getAttribute("dataID"))
<div class="widget" dataID="1"></div>
Or add the dash and use dataset:
console.log(document.querySelector(".widget").dataset.id)
<div class="widget" data-id="1"></div>

Apply javascript function to same ids

I just want to ask let say if we have multiple divs with same id how can we display none them using javascript ?
I tried:
<script>
function filterfunc() {
if(document.getElementById('filter_deductible').value == 'id_50'){
document.getElementById('id_0').style.display = 'none';
document.getElementById('id_50').style.display = 'block';
}
}
</script>
And here is my html divs with same ids:
<div id="id_0">0</div>
<div id="id_0">0</div>
<div id="id_50">50</div>
But its hidding only one div of id id_0 instead of all div having id_0
Any suggestions please
Id must be unique, you should use class like,
<div class="id_0">0</div>
<div class="id_0">0</div>
<div class="id_50">50</div>
And to hide all id_0 use
function filterfunc() {
if($('#filter_deductible').val() == 'id_50'){
$('div.id_0').hide();
$('div.id_50').show();
}
}
It simple using jQuery like
HTML
<select name="filter_deductible" id="filter_deductible">
<option value="id_0">0</option>
<option value="id_50">50</option>
</select>
<div id="id_0">0</div>
<div id="id_0">0</div>
<div id="id_50">50</div>
jQuery
$("#filter_deductible").change(function(){
if($(this).val()=="id_50")
{
$('[id="id_0"]').hide();
}
});
Demo
you should use a class in case there are multiple elements. Or use different ids.
Ids are meant to be unique.
<script>
function filterfunc() {
if(document.getElementById('filter_deductible').value == 'id_50'){
$('.id_0').css("display","none")
$('.id_50').css("display","block")
}
}
</script>
<div class="id_0">0</div>
<div class="id_0">0</div>
<div class="id_50">50</div>
Or
<script>
function filterfunc() {
if(document.getElementById('filter_deductible').value == 'id_50'){
$('.id_0').hide()
$('.id_50').css("display","block")
}
}
</script>
<div class="id_0">0</div>
<div class="id_0">0</div>
<div class="id_50">50</div>
Do not do this. Having multiple elements with the same ids leads to undefined behaviour. If you need to attach information to your dome nodes use data attributes or classes.
Notice how getElementById is singular form? It only ever expects to select and return one element.
That being said, you can probably get away with
document.querySelectorAll("#id_0")
if you want to use javascript functions on dom elements you have to use class not id attribute.
id attribute is unique in whole html document.
try to use jquery.
$.(document).ready(function(){
$("#filter_deductible").change(function(){
var $this = $(this); //instance of element where was changed value
if($this.val() == 'id_50'){
$(".id_0").hide();
$(".id_50").show();
}
});
});
your document html should looks like.
<div class="id_0">0</div>
<div class="id_0">0</div>
<div class="id_50">50</div>
this will works only if you will include jquery library inside tags. And your dom element #filter_deductible allows change event trigger.
hope i helped you
Use classes in this case ID is unique.
<div class="zero">0</div>
<div class="zero">0</div>
<div class="class_50">50</div>
you can use jQuery:
$('.zero').hide();
$('.class_50').show();
The HTML spec requires that the ID attribute to be unique in a page:
If you want to have several elements with the same ID your code will not work as the method getElementByID only ever returns one value and ID's need to be unique. If you have two ID's with the same value then your HTML is invalid.
What you would want to do is use div class="id_0" and use the method getElementsByClassName as this returns an Array of elements
function filterFunc() {
var n = document.getElementsByClassName("id_0");
var a = [];
var i;
while(n) {
// Do whatever you want to do with the Element
// This returns as many Elements that exist with this class name so `enter code here`you can set each value as visible.
}
}

Jquery input value not showing up correctly

I have something very simple to just get an input value.
The code looks like this:
var $a = $('.custom-amount').val();
$('.custom-amount').on('change', function() {
alert($a)
})
And my input:
<div class='custom-amount'>
<input placeholder='Custom Amount' type='text-area'>
For some reason, my alerts are empty. Does anyone see whats going wrong?
Change your selector to $('.custom-amount input'), and get the value after the change event is fired, e.g.
$('.custom-amount input').on('change', function() {
var a = $(this).val();
alert(a);
});
Right now, you are trying to get the value of a div, which won't work. You need to get the value of the input.
Edit: also, it looks like you are trying to display a textarea. Try replacing this...
<input placeholder='Custom Amount' type='text-area'>
With this...
<textarea placeholder='Custom Amount'></textarea>
This may help:
http://jsfiddle.net/d648wxry/
The issue is very simple, you are getting the value of the div element. Instead you should retrieve the value of the input element so the 'custom-amount' class must be added to the input.
Also you need to execute the val() method inside the event to get the value updated.
var $a = $('.custom-amount');
$('.custom-amount').on('change', function() {
alert($a.val());
});
Cause your div has no value. Change your code to:
var $input = $('.custom-amount input');
$input.on('change', function() {
var $a = $input.val();
alert($a)
})
First of all, you only assign to $a outside of the change function. This would be more clear if you kept your code lined up better (see the edit I made to your post). This is the right way to do it:
$('.custom-amount').on('change', function() {
var $a = $('.custom-amount').val();
alert($a)
});
Second of all, the class custom-amount is assigned to a <div> instead of the <input> element. You have to select the <input> element, not the <div>. Change your markup to:
<div>
<input placeholder='Custom Amount' type='text-area' class='custom-amount'>
</div>

How to get inner HTML of element inside a list item, within a delegate?

I have this bit of HTML :
<li eventId="123">
<img src="image.jpeg"/>
<h3 id="eventName">Event Name</h3>
<p id="eventDescription"></p>
</li>
I want to be able to pull out the <h3> and <p> via jQuery so that I can update their values.
I have a delegate bound to the list items, and on click I'm trying to grab hold of <h3> and <p> using :
function eventIdClicked()
{
// This gets hold of "123" OK
theEvent.id = $(this).get(0).getAttribute('eventId');
// How to get the other 2 inner html?
var existingEventName = $(this).get(1).getAttribute('eventName');
var existingEventDesc = $(this).get(2).getAttribute('eventDescription');
$.mobile.changePage("home.html");
}
Am I able to do this?
Maybe something like $(this).find("h3").text() and $(this).find("p").text()?
Very simple jquery.
Also, while it isn't affecting the code in this case, ID's must be unique.
If the ID's aren't unique the elements might as well not have id's.
First off, in your case you should use classes instead of Id's if there are going to be multiple eventnames and eventdescriptions. As for the event handling try passing the event object into the function like so:
function eventIdClicked(evt){
// Now you get get the event target.
// In your case this is the li element.
var target = $(evt.target);
// Now you can pull out the children that you want.
var eventName = target.children(".eventName").text();
var eventDescription = target.children(".eventDescription").text();
// Do more stuff...
}
First, I take for granted that there are several of these <li> so you shouldn't use the id attribute as id have to be unique. I replaced these with a class name.
<li eventId="123">
<img src="image.jpeg"/>
<h3 class="name">Event Name</h3>
<p class="description"></p>
</li>
I cleaned up your syntax using cleaner jQuery methods. I also add the values to the object your are already referencing.
function eventIdClicked()
{
theEvent.id = $(this).attr('eventId');
theEvent.name = $('.name', this).text();
theEvent.description= $('.description', this).text();
$.mobile.changePage("home.html");
}
If you are using HTML5 this would be cleaner:
Replace <li eventId="123">
with <li data-event="{'id':123,'name':Event Name','description':'Event Description'}">
Replace
theEvent.id = $(this).attr('eventId');
theEvent.name = $('.name', this).text();
theEvent.description= $('.description', this).text();
with theEvent = $(this).data('event');
function eventIdClicked()
{
// This gets hold of "123" OK
theEvent.id = $(this).get(0).getAttribute('eventId');
// since you used an id for both tags, you could even ommit the context
var existingEventName = $("#eventName", this);
var existingEventDesc = $("#eventDescription", this);
existingEventName.text("a new event name");
existingEventDesc.text("a new description");
$.mobile.changePage("home.html");
}
Use children function:
var existingEventName = $(this).children('h3')
var existingEventDesc = $(this).children('p');
Now you can use text to grab or modify values. On the other hand those elements also have ids so you can access them using id selector.
If you want to change the innerHTML of the <h3> and <p>, you could use
$('#eventName').html(/*NEW HTML HERE*/);
$('#eventDescription').html(/*NEW HTML HERE*/);
This is assuming the ids are unique in your document

how to get outerHTML with jquery in order to have it cross-browser

I found a response in a jquery forum and they made a function to do this but the result is not the same.
Here is an example that I created for an image button:
var buttonField = $('<input type="image" />');
buttonField.attr('id', 'butonFshi' + lastsel);
buttonField.val('Fshi');
buttonField.attr('src', 'images/square-icon.png');
if (disabled)
buttonField.attr("disabled", "disabled");
buttonField.val('Fshi');
if (onblur !== undefined)
buttonField.focusout(function () { onblur(); });
buttonField.mouseover(function () { ndryshoImazhin(1, lastsel.toString()); });
buttonField.mouseout(function () { ndryshoImazhin(0, lastsel.toString()); });
buttonField.click(function () { fshiClicked(lastsel.toString()); });
And I have this situation:
buttonField[0].outerHTML = `<INPUT id=butonFshi1 value=Fshi src="images/square-icon.png" type=image jQuery15205073038169030395="44">`
instead the outer function I found gives buttonField.outer() = <INPUT id=butonFshi1 value=Fshi src="images/square-icon.png" type=image>
The function is:
$.fn.outer = function(val){
if(val){
$(val).insertBefore(this);
$(this).remove();
}
else{ return $("<div>").append($(this).clone()).html(); }
}
so like this I loose the handlers that I inserted.
Is there anyway to get the outerHTML with jquery in order to have it cross-browser without loosing the handlers ?!
You don't need convert it to text first (which is what disconnects it from the handlers, only DOM nodes and other specific JavaScript objects can have events). Just insert the newly created/modified node directly, e.g.
$('#old-button').after(buttonField).remove();`
after returns the previous jQuery collection so the remove gets rid of the existing element, not the new one.
Try this one:
var html_text = `<INPUT id=butonFshi1 value=Fshi src="images/square-icon.png" type=image jQuery15205073038169030395="44">`
buttonField[0].html(html_text);
:)
Check out the jQuery plugin from https://github.com/darlesson/jquery-outerhtml. With this jQuery plugin you can get the outerHTML from the first matched element, replace a set of elements and manipulate the result in a callback function.
Consider the following HTML:
<span>My example</span>
Consider the following call:
var span = $("span").outerHTML();
The variable span is equal <span>My example</span>.
In the link above you can find more example in how to use .outerHTML() plug-in.
This should work fine:
var outer = buttonField.parent().html();

Categories

Resources