I'm trying to display the jQuery custom attribute in alert or console.
I tried using console.log() to log my custom data attribute but its not displaying the value.
I'm trying to display this value data-something, here's my code:
When I tried to display the value in alert it shows undefined; how to fix it?
// create a UL element
var ul = $('<ul></ul>');
// add some LI elements
ul.append(
$('<li class="bear" data-type="panda">panda bear</li>'),
$('<li class="bear" data-type="koala">koala bear</li>'),
$('<li class="wallaby" data-type="kangaroo">kangaroo</li>')
);
// this won't work because our UL is not in the dom yet
console.log($('.bear').length); //=> 0
// let's just pick the bears in our UL using our UL as the context
var bears = $('.bear', ul);
console.log(bears); //=> [li.bear, li.bear]
// lets loop through and see data attributes
bears.each(function() {
console.log($(this).attr('data-type'));
});
//=> "panda"
//=> "koala"
I have changed few of the code !
<div id="statusHtml">
</div>
<script>
// it will help to get statusHtml div tag using jquery.
var statusHtmlArr=$("#statusHtml");
$.each($('.loc-li'),funciton(){
alert("print the value in alert" + $(this).attr('data-test'));
});
/*OR*/
alert("print the value in alert" + $('.loc-li').attr('data-test'));
</script>
to show the attribute in jquery you have to use "attr()" function
Check Fiffle
Related
When I press the Submit button if any error is generated then code create a span element.
My question is how I can clear the old error from the error container element, or if not possible then please sum up the errors.
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="'+i+'"]');
el.after($('<span style="color: red;">'+error[0]+'</span>'));
});
I tried remove() but I cannot do it.
Thanks
you can remove the span with next().
next() finds the next sibling to the input field you are referring to.
it will give you the span:
el.next().remove();
you can use a class on the span f.e. class="validation-span"
el.next(".validation-span").remove();
this will make sure you only remove the span and no other element if existent :)
Add an span element after the input and set its HTML each time instead of using .after.
<input name="yourName">
<span class="errors"></span>
<script>
$(document).find('[name="'+i+'"] + .errors')
.html('<span style="color: red;">'+error[0]+'</span>');
</script>
I updated the both way you want, please pick which is more suitable to you
function logErrorCleanSpan(errorMessage){
$('#errorContainer').text(errorMessage);
}
logErrorCleanSpan("Hello");
logErrorCleanSpan("Jarvis");
function logErrorAppendSpan(errorMessage){
var span = $("<span>"+errorMessage+"</span>");
$('#errorContainerSpanAppend').append(span);
}
logErrorAppendSpan("1. Hello ");
logErrorAppendSpan("2. Jarvis ");
#errorContainerSpanAppend{
display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Append Error and clean the previous error<h3>
<span id="errorContainer"></span>
<h3>Append Error and keep the older one<h3>
<span id="errorContainerSpanAppend"></span>
Assign a id with index to span after each click remove previous span using id
Use jquery remove
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="'+i+'"]');
el.after($('<span id="error'+i+'" style="color: red;">'+error[0]+'</span>'));
if($(document).find('span#error+i - 1+')) {
$( "span#error+i - 1+" ).remove();
}
});
this is just an example code not correct code.
For our shops we use the NiceSelect library, but we ran into an issue:
When we try to override a DOM element in the new selection-dropdown for our payment options, our changes get overriden right back. This only happens to the element called 'current', which I will explain down below:
CODE
//Make the generated select into a nice select
$('#payment_type').niceSelect();
//Add additional fees to items, where needed, and bind an event to those items
if(!additionalFeesAdded){
$('.nice-select.small.payment_type ul > li').each(function(i){
var af = additionalFeeArray[i];
if(af != "NaN" && af != "0.00"){
$(this).append("<label class='additional-fee selection'> + € " + af + "</label>");
$(this).on('click', function(){
$('.nice-select.small.payment_type .current').trigger('contentchanged');
});
}
});
//Hocus pocus to make the additional fee float to the right (TEST DATA)
$('.nice-select.small.payment_type .current').bind('contentchanged', function(){
var paymentType = "Method";
var additionalFee = "Fee";
console.log($(this).html()); //Returns DOM before change
$(this).html(paymentType + "<label class='additional-fee'>" + additionalFee + "</label>");
console.log($(this).html()); //Returns DOM after change
});
}
additionalFeesAdded = true;
DOM SETUP
<div class="nice-select small payment_type open" tabindex="0">
<span class="current">SELECTED OPTION APPEARS HERE</span>
<ul class="list">
<li data-value="" class="option selected focus">Select a payment type </li>
<li data-value="3" class="option">OPT.1<label class="additional-fee selection"> + € 0.60</label></li>
<li data-value="4" class="option">OPT.2</li>
<li data-value="6" class="option">OPT.3<label class="additional-fee selection"> + € 0.40</label></li>
<li data-value="27" class="option">OPT.4<label class="additional-fee selection"> + € 0.50</label></li>
</ul>
</div>
This is pretty much what's being done to make an additional fee float to the right. This works in the li items the library makes, but not the DOM element that shows the selected option.
I tried adding a custom event to mimic an onChange(), but the latter DOM printed to the console never makes it to the element itself:
How the element always comes back:
How it should be:
So in short: Something I try to manipulate doesn't want to get manipulated, and I don't know what's going wrong. Is anyone able to help me with/see the issue?
If more information is required, I am happy to oblige.
The nice select library replace .current text after option has been changed.
You need to call your handler after the library did its work.
So remove click binding in cycle and contentchanged handler.
And add click handler like this
$(document).on('click.nice_select', '.nice-select .option:not(.disabled)', function(event) {
$current = $('.nice-select .current');
var paymentType = "Method";
var additionalFee = "Fee";
console.log($current.html()); //Returns DOM before change
$current.html(paymentType + "<label class='additional-fee'>" + additionalFee + "</label>");
console.log($current.html()); //Returns DOM after change
});
I made a plunker with working example
I check the code but the following part does not work for me:
$current = $('.nice-select .current');
Then I change the .current to .selected and it returns the selected li element, maybe this is a change in the new version of nice-select.
I am currently trying to create a hidden field in a current list (li) in which I can pass another field other than just the text value.
Here is what I have so far:
HTML:
<ul id = "playlist" class="mejs-list" style="background: #00BFFF;list-style: none; padding: 0;list-style-type: none;width: 300px; height: 300px;overflow: auto" >
<li data-leaves="47" class="current">Test</li>
<li data-leaves="47">Test2</li>
</ul>
Javascript (I simplified the code):
$(".mejs-list li").click(function() {
var audio_src = $(this).text();
alert(audio_src)
var test = $(this).dataset.leaves
alert(test )
});
I get a display for "audio_src" no problem since this is simply the "text" of the item however I can not get the custom field to pass through.
Any ideas?
jQuery objects have no dataset proprty. Don't "cast" this to a jQuery Object:
$(".mejs-list li").click(function () {
var audio_src = $(this).text();
alert(audio_src);
var test = this.dataset.leaves;
alert(test);
});
Demo
Also learn how to use console.log for debugging. You can get alot more info that way, you can log and inspect objects to the console.
I think you should use $(this).attr("dataset-leaves") instead of $(this).dataset.leaves.
BTW, it is best practise to end each statement with a semi-comma.
Correction: should be $(this).attr("data-leaves")
use jQuery data() to return the value of data-leaves.
$('.mejs-list li').click(function() {
var audio_src = $(this).text(),
test = $(this).data('leaves');
alert('audio source: '+ audio_src + '\n data-laves: '+ test);
});
Demo: http://jsfiddle.net/pWuh9/
I am using jquery inside the javascript function to hide & show div.
I need to show only div "Area" while hide other div
This one works, when i directly put the name of the div to hide & show :---
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script>
function area_visible()
{
$('.Area').show();
$('.Area-1').hide();
$('.Area-2').hide();
$('.Area-3').hide();
}
This one does not works if i try to access using array of div class, even alert message is not displayed 4 times for loop :----
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script>
var area_id = [
"Area" , "Area-1", "Area-2", "Area-3"
];
function area_visible()
{
$(area_id).each(function(index, element) {
if(element != area_id[0] )
{
$("#" + element).hide();
}
alert('11');
});
}
Please suggest. How to hide and show div by taking there name from an array (and i want to use jquery inside javascript function) ?
Change
$("#" + element).hide();
to
$("." + element).hide();
You are trying to target an ID you must use . to target class.
in your first function you are using class $('.Area-1') and the second function you are selecting with ID $("#"+element)
so the fix is easy just change '#' to '.' in the second function
You have to change your id selector to a class selector and initiate the function:
$("." + element).hide(); // for your second function.
and initialize your func:
area_visible(); // for both it will work.
UPDATE: A commenter told me to change some codes, this is the new code and its not working neither.
I'm creating a Facebook-Like chat. It gets the latest messages "Not Read" from a JSON file and it appends the text to an "UL" element vía "LI" into a box. If the box doesn't exist, it creates and attach the text. I want that when I click that div, it hides using margin-bottom negative, and when I click it again it shows by Margin-Bottom:0. Please help me since it's just not working.
function showChat(id){
$(this).animate({marginBottom : "0"}).removeClass("hidden_box").addClass("active_box").removeAttr('onclick').click(function(){
hideChat(Id);
});
}
function hideChat(id){
$(this).animate({marginBottom : "-270px"}).removeClass("active_box").addClass("hidden_box").click(function(){
showChat(Id);
});
}
function getOnJSON(){
//Creating Variables that will be used
var from;var to;var msg_id;var msg_txt;
//Getting the data from the json file
$.getJSON("/ajax/chat.json.php",function(data){
//Repeat for each result
$.each(data.notif, function(i,data){
//Getting a var to info
from = data.from;to = data.to;msg_id = data.id;msg_txt = data.text;
//check if div exists
if ($("#chat_"+from+"_lp").length === 0){
//If not, create the div
$("#boxes").append('<div id="chat_'+from+'_lp" class="chat_box hidden_box clickable_box"></div>');
//Add the senders name
$("#chat_"+from+"_lp").append('<div id="'chat_+from+'_nick" class="chat_name">'+from+'</div>');
//Add the chats UL
$("#chat_"+from+"_lp").append('<ul id="chat_'+from+'_txt" class="chat_txt"></ul>');
//Add the message text
$("#chat_"+from+"_lp").append('<li id="' + msg_id + '">'+ msg_txt+'</li>');
//Add event handler for each div
$('#chat_'+from+'_lp').click(function() {showChat(this);});
//If div exists just add the text
}else{
//Add the message text
$("#chat_"+from+"_txt").append('<li id="' + msg_id + '">'+ msg_txt+'</li>');
//Add event handler for each document
$('#chat_'+from+'_lp').click(function() {showChat(this);});
//Close If
}
//Close data for each item
});
//Close JSON
});
//Close Function
}
UPDATE 2: in order to stop making and appending things, I made an unique HTML string that is going to be appended.
new_chat_string = '<div id="chat_'+from+'_lp" class="chat_box hidden_box clickable_box"><div id="'chat_+from+'_nick" class="chat_name">'+from+'</div><ul id="chat_'+from+'_txt" class="chat_txt"><li id="' + msg_id + '">'+ msg_txt+'</li></ul></div>';
$("#boxes").append(new_chat_string);
use class instead of id
<div id="chat_sender_lp" class="chat_box hidden_box clickable_box sender-click"
then
$('.hidden_box.sender-click').live('click', function(){
$(this).slideToggle(500);
});
After:
$("#boxes").append('<div id="chat_'+from+'_lp" class="chat_box hidden_box clickable_box" ><div id="name">'+from+'</div><ul id="chat_'+from+'_txt" class="chat_txt"><li id="' + msg_id + '">'+ msg_txt+'</li></ul></div>');
Add the event handler for the inserted element:
$('#chat_'+from+'_lp').click(function() { showChat(this) })
"this" passes a DOM reference to itself.
Keep in mind that you're adding: <div id="name"> every time. IDs must be unique. Use a class name instead.
EDIT:
Appending to the DOM is really quite slow. It's actually more efficient to build up your HTML as a string and just insert it in one go. Also, you only really need to stick and ID on the wrapping element. Everything else can be derived from that using a jQuery selector. It helps you write much cleaner code.
Here's the string you need to append:
'<div id="chat_'+msg_id+'" class="chat_box hidden_box clickable_box">
<div class="chat_name">'+from+'</div><ul class="chat_txt"><li>
'+msg_txt+'</li></ul></div>'
If you wanted to select chat name later, you'd use: $('chat_1 .chat_name').html()
It also makes more semantic sense to hook up your click handler to an A tag. So you'd use:
$('#chat_'+msg_id).find('a').click(function() {showChat(this);});
The code is a lot cleaner and easier to follow this way. I hope this helps.