Javascript handle 2 data attribute - javascript

I need to use data attribute in my html
like
<div id="userlist" data-user="A.A.M"></div>
then I need to alert the data-user
I used
var userlist = document.getElementById("userlist");
var show = userlist.getAttribute("data-user");
alert(show);
My question is how to handle many data-user in the html like
<div id="userlist" data-user="A.A.M"></div>
<div id="userlist2" data-user="A.A.M2"></div>
to alert A.A.M and A.A.M2
Thanks in advance and sorry for my bad English.

You could select your elements by attribute.
$("div[data-user]").each(function() {
var user = $(this).data("user");
alert(user);
});
If you have multiple attributes per element (<div data-user='something' data-another='another'></div>), you can also access those in the same way:
$("div[data-user]").each(function() {
var user = $(this).data("user");
var another = $(this).data("another");
alert(user + ", another: " + another);
});

you know how to alert 1, alert 2:
alert at the same time:
var data1 = document.getElementById("userlist").getAttribute("data-user");
var data2 = document.getElementById("userlist2").getAttribute("data-user");
var data = data1 +"\n" + data2; //"\n" can be other separators you like
alert(data)
if you have many of them, you can use jQuery:
add this in your , before any other js code.
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
then :
$("div[id^=userlist]").each(function(){
alert($(this).attr("data-user"));
});

Calling getElementById on both should work. If you want to iterate you can try to use getElementsByTagName or getElementsByClassName. If you want to select any arbitrary element with the attribute data-user, you can either use querySelectorAll, or check out jQuery, and use $("[data-user]") as a selector.
Does that answer your question?

Related

clone or append a variable in a new div?

I have this Html <h1 class="count" role="status">Search results 546</h1>
I'm trying to clone only the numerical '546' of that div and display it inside another div 'h2.count'
I manage to call only the numerical value in an alert via:
var price = $('h1.count').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
alert(parsedPrice.toFixed(0));
Otherwise , when i try to make it display in the div h2.count instead of an alert, it is not working.
I have try the below:
var price = $('h1.count').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
$parsedPrice.appendTo('h2.onlycount');
Any thought of what i am doing wrong ?
Thanks a lot guys !
I guess that your two html elements are unique so, using id's instead of classes (and native js), try this :
html :
<h1 id="count">Search results 541</h1>
<h2 id="onlycount"></h2>
js :
var price = document.getElementById('count').innerText;
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
document.getElementById('onlycount').innerText = parsedPrice;
https://jsfiddle.net/f3rj2bnv/
And if you want to keep on using jQuery (replace "#" with "." if you want or have to use classes instead of ids in your html elements) :
var price = $('h1#count').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
$('h2#onlycount').text(parsedPrice)
The content used by .appendTo() should be
"a selector expression or as markup created on the fly"
Since in your example neither is true, try this:
var price = $('h1.count').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
$('h2.onlycount').text(parsedPrice);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="count" role="status">Search results 546</h1>
<h2 class="onlycount" role="status"></h1>
Can use text(function)
$('h2.onlycount').text(function(_, existingText){
return existingText + $('h1.count').text().replace(/([^0-9\.])/g, '');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="count" role="status">Search results 546</h1>
<h2 class="onlycount"></h2>

jquery - how can I select element after '.first()' using?

How can I select html tag after using jquery function called .first() ?
HTML
<html>
<head> </head>
<body>
<div>
<a>
<img id="#hello">
</a>
</div>
<div></div>
</body>
</html>
JS (JQuery)
var elemFirst = $(div).first();
var selectImg = elemFirst.$('img#hello');
// var selectImg = elemFirst.find('img'); <- It working but I want to select manual
selectImg.addClass('some-css');
With Respect
You can use $('child','parent') selector,
var elemFirst = $('div').first();
var selectImg = $('#hello',elemFirst); //or just $('img',elemFirst);
Also, your id has a #, it should be just id="hello".
If you need to keep this value in Id, use
var selectImg = $('img[id="#hello"]',elemFirst);
You can use find():
var selectImg = elemFirst.find('img#hello');
But you have an id of the image, so, you just can do this:
$('img#hello')
Because id is unique.
Use find()
elemFirst.find('img#hello');
This will search for direct and nested elements with the provided selector.
Alternatively, you can do
$('div:first #hello')
or even just
$('#hello')
since you are using an id which should be unique.
As in html the id be unique in html so striaghtly write
$("#\\#hello").addClass('some-css');
or
var selectImg = elemFirst.find('img[id="#hello"]');
Fiddle

jQuery selector by form index and input name

Take the following page with two forms with different classes but each form has an input with the same name.
<form class='first_form'>
<input name='test' value='1' />
</form>
<form class='second_form'>
<input name='test' value='3'/>
</form>
I can get the form index and I know the name of the input but I do not know the index of the input.
Is there a way to chain a selector with the form index and the input name to get the value?
I have tried chaining but nothing seems to work
var inputName = 'test';
Var formIndex = 1;
$('*[name="' + inputName + '"]' +' ' + '$("form").eq(' + formIndex + ')').val();
FIDDLE
var formIndex=0;
var inputName="txtbox";
vall= $("form:eq("+ formIndex+") input[name= "+ inputName +" ]").val();
alert(vall);
your order was wrong
Untested, but could you do:
$('form:nth-of-type(1) input[name="test"]').val();
$("form:nth-child("+formIndex+") input[name='"+inputName+"']").val();
You could do in a more clever way:
var fieldName = 'test';
var formId = '.first_form'
$('form'+formId+' input[name='+fieldName+']).val()
Instead of index, use named selectors, like id or class. It will help you in the future find the correct form (when you will have more than 5, it will be hard to count witch one you are looking at :) )
But that is too complex:)
I would propose something like this:
var currentForm = $('form'+formId);
currentForm//here you can put a log into console if element has not been found and find that bug sooner.
currentForm.find('input[name='+fieldName+']').val()
You can access the form's element directly within the DOM using either of:
document.forms[formIndex]
document.forms[formName]
You can then reference an input element by name using:
document.forms[formIndex][inputName]
document.forms[formName][inputName]
Then just wrap it in $(...) to get yourself a jQuery collection. In your case:
var inputName = 'test',
formIndex = 1;
$(document.forms[formIndex][inputName]);
I imagine this is by far the most performant way, and it's readable too.
To add a little detail, document.forms is an HTMLCollection of all HTMLFormElements within a document. And given any HTMLCollection or HTMLFormElement you can access named elements within them as properties.

JQuery: Selecting elements with unique class AND id

I have this html code:
<div class="category" id="154"> Category </div>
<div class="category2" id="156"> Category2 </div>
<div class="category3" id="157"> Category3 </div>
<div class="category4" id="158"> Category4 </div>
<input type="text" />
So in example if I write a id in text box, how to select div .category with this ID and get inner HTML text. With jQuery
so you only need to use the ID as this is a unique value (or should be)
var html = $("#154").html();
NOTE: If you do have duplicate ID values in use then it is important to note that JQuery will only select the first one.
if you want to do this when a textbox value is entered you could do this on the textbox change event...
$("input").change(function(){
var id = $(this).val();
var element = $("#" + id);
if(element){
var html = element.html();
//do something with html here
}
});
NOTE: you may want to put an ID value on your textbox to ensure you get the correct control
Although I strongly suggest you find a way around using duplicate ID values, you could have a function like this to get the DIV you want...
function GetContent(className, id) {
var result = null;
var matchingDivs = $("." + className);
matchingDivs.each(function(index) {
var div = $(matchingDivs[index]);
if (div.attr("id") == id) {
result = div.html();
}
});
return result;
}
Click here for working example
I recommend you give the textbox an ID, in case you add other textboxes to the page.
But if you only have the 1 text input, the following would work:
var id = $('input:text:first').val();
var innerHtml = $('#' + id).html();
Here is a jsFiddle that will alert the html using this technique whenever the text in the textbox changes.
$("#id.class")
will select the necessary element by both class and ID (replacing id and class with their respective names, of course).
Adding .html() to the end will get you the content.
i.e:
$("#id.class").html()

How to render a javascript variable in an HTML attribute using jQuery

Using the following code:
<div class="whatever" addthis:title="Hi, your name is [firstName]"></div>
If I have a JS variable like this
var name = John
How would I replace the "[firstName]" with my JS variable in the first code snippet using jQuery?
It's ok if I need to set the attribute using jQuery to begin with like:
$('.whatever').attr( 'addthis:title', 'Hi, your name is [firstName].' );
Simply run replace on your string...:
var name = 'John';
$('.whatever').attr('addthis:title', function(i, attr){
return attr.replace('[firstName]', name);
});
P.S. Are you sure you want an attribute addthis:title, not simply title? That's invalid HTML! If you want to create your own attributes, prefix them with data-:
<div class="whatever" data-addthis-title="Hi, your name is [firstName]"></div>
Did you try it? Your example code contains all the pieces you need.
var name = "John";
var element = $('.whatever');
var newAttrValue = element.attr('addthis:title').replace(/\[firstName\]/, name);
element.attr('addthis:title', newAttrValue);

Categories

Resources