Find an element value with jQuery - javascript

In the following HTML markup, how can I get the value of the input field which has the name module_id[], by clicking on the span class .click.
HTML:
<div class="module">
<div class="info">..</div>
<div class="ctrl"><span class="click">Click</span></div>
<input type="hidden" value="module1" name="module_id[]" />
<input type="hidden" value="title" name="module_title[]" />
</div>
I have tried this:
jQuery:
$('.module').on('click','.click',function(){
var target_module = $(this).parent();
var module_id = target_module.find('input[name=module_id\\[\\]]').val();
alert(module_id);
});
Demo:
http://jsfiddle.net/FKdNJ/

$(this).parent(); is giving you the <div class="ctrl"> instead.
You could use $(this).parent().parent(), but a more flexible solution is to use closest() instead;
$(this).closest('.module');
You can see this working here; http://jsfiddle.net/FKdNJ/5/
FWIW, you could also change your approach completely, and use e.delegateTarget to retrieve the .module element directly (http://jsfiddle.net/FKdNJ/7/);
$('.module').on('click','.click',function(e){
var target_module = $(e.delegateTarget);
var module_id = target_module.find('input[name=module_id\\[\\]]').val();
alert(module_id);
});

With:
$('input[name="module_id[]"').val();
jsFiddle example 1
$('.module').on('click', '.click', function () {
console.log($('input[name="module_id[]"').val());
});
If you have more than one set of this block of code, use $(this).closest('.ctrl').next().val():
as in:
$('.module').on('click', '.click', function () {
console.log($(this).closest('.ctrl').next().val());
});
jsFiddle example 2

Try this
$('.module').on('click','.click',function(){
alert($(this).closest('.module').find('[name="module_id[]"]:first').val())
});
http://jsfiddle.net/FKdNJ/3/

Try this. You're probably better off using html 5 data- attributes if possible.
$('span.click').click(function(){
var moduleId = $(this).closest("div.module").find("input[name='module_id[]']").val()
alert(moduleId);
});

I have added a answer in fiddle:
$('.click').on('click',function(){
alert($('input[name=module_id\\[\\]]').val());
})
http://jsfiddle.net/FKdNJ/6/

Related

Get next textarea outside div without id

I need to get the next textarea, but I'm not being able with next or even find.
Sample code HTML:
<div>
<div class="guides_chapters_button" onclick="surroundtest('[center]', '[/center]');">Center</div>
<div class="guides_chapters_button" style="text-decoration: underline;" onclick="surround('[u]', '[/u]');">u</div>
</div>
<textarea class="guides_chapters_textarea" id="textareamatch" name="matchupm" rows="7" cols="25"></textarea>
JS:
window.surround = function surround(text2,text3){
$("#textareamatch").surroundSelectedText(text2, text3);
}
function surroundtest(text2,text3){
var c = $(this).parent().next('textarea');
c.surroundSelectedText(text2, text3);
}
JS FIDDLE: http://jsfiddle.net/qmpY8/1/
What I need working is surroundtest, the other is an example working but using the id. I would love to replace that one because Im usinc cloned objects.
The this statement in surroundtest applies to the window object and not the element. What you should do is to change the function definition as so:
function surroundtest(element, text2,text3){
var c = $(element).parent().next('textarea');
...
}
And the HTML accordingly:
<div class="guides_chapters_button" onclick="surroundtest(this, '[center]', '[/center]');">Center</div>
If this is the HTML you are going with, then .closest() can also be used to get the textarea element.Like below:
var c = $(element).parent().closest('textarea');

jQuery multiple reoccurrence replace innerHTML

I have the following script works for the replace with jQuery in innerHTML.
HTML code
<input type="submit" name="replace" id="replace" value="Replace" />
<div class="my_div">Default1 content1</div>
<div class="my_div">Default2 content2</div>
java script
$('#replace').click(function() {
$('.my_div').html(function( idx, oldHtml){
return oldHtml.replace(/Default1|content1|Default2|content2/gi, 'symbol1');
});
});
But I couldn't modify the script for multiple unique replacement. Example I want to replace
Default1 to symbol1
Default2 to symbol2
content1 to symbol3
content2 to symbol4
the following doesn't work
$('#replace').click(function() {
$('.my_div').html(function( idx, oldHtml){
return oldHtml.replace(/Default1/gi, 'symbol1');
return oldHtml.replace(/Default2/gi, 'symbol2');
return oldHtml.replace(/content1/gi, 'symbol3');
return oldHtml.replace(/content2/gi, 'symbol4');
});
});
Also I had early script based on id attribute, which is more than 500 replace lines. Is it possible that I can include similar structure in this new jQuery class attribute?
var str=document.getElementById("my_id").innerHTML;
var n=str.replace("Default1","symbol1");
var n=str.replace("Default2","symbol2");
document.getElementById("my_id").innerHTML=n;
}
Thanks a lot, you guys helped me a lot. :)
Question 1 :
Replace
return oldHtml.replace(/Default1/gi, 'symbol1');
return oldHtml.replace(/Default2/gi, 'symbol2');
return oldHtml.replace(/content1/gi, 'symbol3');
return oldHtml.replace(/content2/gi, 'symbol4');
with
return oldHtml.replace(/Default1/gi, 'symbol1')
.replace(/Default2/gi, 'symbol2')
.replace(/content1/gi, 'symbol3')
.replace(/content2/gi, 'symbol4');
Question 2 :
Replace
var str=document.getElementById("my_id").innerHTML;
var n=str.replace("Default1","symbol1");
var n=str.replace("Default2","symbol2");
document.getElementById("my_id").innerHTML=n;
with
var $div = $('#my_id');
$div.html(
$div.html().replace("Default1","symbol1")
.replace("Default2","symbol2")
);
(if you use jQuery, no need for those getElementById)

How Do I Replace/Change The Heading Text Inside <h3></h3>, Using jquery?

How do I change/replace the <h3> text: "Featured Offers" using javascript to say "Public Offers" instead?
</div> <!-- FEATURED OFFERS -->
<div class="panel">
<div class="head">
<h3>Featured Offers</h3>
</div>
<div class="body">
<table>
<thead>
<tr>
If you can select it, you can manipulate it.
Try this:
$(".head h3").html("your new header");
But as others mentioned, you probably want head div to have an id.
you don't - not like this.
give an id to your tag , lets say it looks like this now :
<h3 id="myHeader"></h3>
then set the value like that :
myHeader.innerText = "public offers";
$("h3").text("context")
Just use method "text()".
The .text() method cannot be used on form inputs or scripts. To set or
get the text value of input or textarea elements, use the .val()
method. To get the value of a script element, use the .html() method.
http://api.jquery.com/text/
Give an id to h3 like this:
<h3 id="headertag">Featured Offers</h3>
and in the javascript function do this :
document.getElementById("headertag").innerHTML = "Public Offers";
try this,
$(".head h3").html("New header");
or
$(".head h3").text("New header");
remember class selectors returns all the matching elements.
Something like:
$(".head h3").html("Public offers");
jQuery(document).ready(function(){
jQuery(".head h3").html('Public Offers');
});
You can try:
var headingDiv = document.getElementById("head");
headingDiv.innerHTML = "<H3>Public Offers</H3>";
Hope that help someone:-
Element with a class attribute with the value of "className":
<h3 class="className"></h3>
You will make a refernce of by the class name:
const newTitle = document.querySelector(".className");
Then change the content:
newTitle.textContent = "New Title";

How can I get the data-id attribute?

I'm using the jQuery Quicksand plugin. I need to get the data-id of the clicked item and pass it to a webservice.
How do I get the data-id attribute? I'm using the .on() method to re-bind the click event for sorted items.
$("#list li").on('click', function() {
// ret = DetailsView.GetProject($(this).attr("#data-id"), OnComplete, OnTimeOut, OnError);
alert($(this).attr("#data-id"));
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<ul id="list" class="grid">
<li data-id="id-40" class="win">
<a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">
<img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id" />
</a>
</li>
</ul>
To get the contents of the attribute data-id (like in <a data-id="123">link</a>) you have to use
$(this).attr("data-id") // will return the string "123"
or .data() (if you use newer jQuery >= 1.4.3)
$(this).data("id") // will return the number 123
and the part after data- must be lowercase, e.g. data-idNum will not work, but data-idnum will.
If we want to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:
Through JavaScript
<div id='strawberry-plant' data-fruit='12'></div>
<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'
// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>
Through jQuery
// Fetching data
var fruitCount = $(this).data('fruit');
OR
// If you updated the value, you will need to use below code to fetch new value
// otherwise above gives the old value which is intially set.
// And also above does not work in ***Firefox***, so use below code to fetch value
var fruitCount = $(this).attr('data-fruit');
// Assigning data
$(this).attr('data-fruit','7');
Read this documentation
Important note. Keep in mind, that if you adjust the data- attribute dynamically via JavaScript it will not be reflected in the data() jQuery function. You have to adjust it via data() function as well.
<a data-id="123">link</a>
JavaScript:
$(this).data("id") // returns 123
$(this).attr("data-id", "321"); //change the attribute
$(this).data("id") // STILL returns 123!!!
$(this).data("id", "321")
$(this).data("id") // NOW we have 321
If you are not concerned about old Internet Explorer browsers, you can also use HTML5 dataset API.
HTML
<div id="my-div" data-info="some info here" data-other-info="more info here">My Awesome Div</div>
JavaScript
var myDiv = document.querySelector('#my-div');
myDiv.dataset.info // "some info here"
myDiv.dataset.otherInfo // "more info here"
Demo: http://html5demos.com/dataset
Full browser support list: http://caniuse.com/#feat=dataset
You can also use:
<select id="selectVehicle">
<option value="1" data-year="2011">Mazda</option>
<option value="2" data-year="2015">Honda</option>
<option value="3" data-year="2008">Mercedes</option>
<option value="4" data-year="2005">Toyota</option>
</select>
$("#selectVehicle").change(function () {
alert($(this).find(':selected').data("year"));
});
Here is the working example: https://jsfiddle.net/ed5axgvk/1/
This piece of code will return the value of the data attributes. For example: data-id, data-time, data-name, etc.
I have shown it for the id:
Click
JavaScript: Get the value of the data-id -> a1
$(this).data("id");
JQuery: This will change the data-id -> a2
$(this).data("id", "a2");
JQuery: Get the value of the data-id -> a2
$(this).data("id");
HTML
<span id="spanTest" data-value="50">test</span>
JavaScript
$(this).data().value;
or
$("span#spanTest").data().value;
ANS: 50
Accessing the data attribute with its own id is a bit easy for me.
$("#Id").data("attribute");
function myFunction(){
alert($("#button1").data("sample-id"));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="button1" data-sample-id="gotcha!" onclick="myFunction()"> Clickhere </button>
var id = $(this).dataset.id
works for me!
I use $.data:
//Set value 7 to data-id
$.data(this, 'id', 7);
//Get value from data-id
alert( $(this).data("id") ); // => outputs 7
Using jQuery:
$(".myClass").load(function() {
var myId = $(this).data("id");
$('.myClass').attr('id', myId);
});
Try
this.dataset.id
$("#list li").on('click', function() {
alert( this.dataset.id );
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<ul id="list" class="grid">
<li data-id="id-40" class="win">
<a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">
<img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id >>CLICK ME<<" />
</a>
</li>
</ul>
for pure js
let btn = document.querySelector('.your-btn-class');
btn.addEventListener('click',function(){
console.log(this.getAttribute('data-id'));
})
The issue is you are not specifying the option or selected option of dropdown or list, Here is an example for dropdown, i am assuming a data attribute data-record.
$('#select').on('change', function(){
let element = $("#visiabletoID");
element.val($(this).find(':selected').data('record'));
});
For those looking to dynamically remove and re-enable the tooltip, you can use the dispose and enable methods. See .tooltip('dispose').
HTML 5 introduced dataset: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset, the browser compa
But for older browser you can use getAttribute method to get the data-* attributes.
const getDataAttr = (id) => {
if(currentNode.dataset) return currentNode.dataset[id];
return currentNode.getAttribute("data-"+id);
}
The reason to use dataset is constant lookup time, get attribute would not be a constant time lookup, it'll go through all the attributes of the html element and then return the data once it'll find the exact attribute match.
The reason to provide this answer is that nobody mentioned about the browser compatibility and lookup time with the given solution, although both of these solutions are already given by people.
I have a span. I want to take the value of attribute data-txt-lang, which is used defined.
$(document).ready(function ()
{
<span class="txt-lang-btn" data-txt-lang="en">EN</span>
alert($('.txt-lang-btn').attr('data-txt-lang'));
});

How to add a class to empty h1 with jQuery?

I'd like to add a class 'hideme' to a empty div.
<div id="infocontent" class="grid_15 prefix_1">
<h1 id="mainhead" class="grid_15 alpha omega" ></h1>
<div id="infoinner" class="grid_13 prefix_1 suffix_1 alpha omega">
<FORM ACTION="command.asp" METHOD="get" NAME="artForm">
....
.....
I made this but something wrong.
$function(){
var contentid = $('#mainhead');
var content = contentid.html();
if (content===''){
contentid.addClass('hideme');
}
})
Update: Sorry it was empty h1.
Your <div> isn't empty; it contains all subsequent content until the end of <div id="infocontent">.
Close your tags!
always!
As other people have mentioned, your code can be simplified by using the :empty selector:
$('#mainhead:empty').addClass('hideme');
If the <div> is not empty, this selector will not match any elements, and the line will do nothing.
You can try this:
$function(){
var contentid = $('#mainhead');
var content = contentid.html();
if (contentid.is(':empty')==''){
contentid.addClass('hideme');
}
})
Try this instead:
if (contentid.is(':empty')) {
contentid.addClass('hideme');
}
Try,
$("div:empty").addClass('hideme');

Categories