How to check data present or not in html id - javascript

I have a HTML paragraph, if it is empty I want to show alert using jquery how.? I have tried the following:
var abc= $("#foo").text();
var abc= $("#foo").data();
var abc= $("#foo").val();
if (abc== '') { alert('working'); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="foo"></p>

val() is used to retrieve the value of an input, not the text node value of an element. data() is used to retrieve data values for an element, not its text node value.
To check if the element does not contain anything, you should used text(). It's also worth noting that you may (or may not) need to use $.trim() to ignore whitespace, and to also check for child elements that do not have any text using children():
var $p = $('#foo'),
empty = ($.trim($p.text()) == '' && !$p.children().length);
console.log(empty);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="foo"></p>
Better still though, rather than rolling your own function for this, you can use jQuery's is() function, coupled with the :empty selector:
console.log( $('#foo').is(':empty') );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="foo"></p>

try this :
var abc = $("#foo").text()
if(!abc) {
alert('not working');
} else {
alert('working');
}

Related

How to add hyperlink in jquery replace

I have the following script and I want to replace barbel with a href
$(".text_div, p").text(function() {
return $(this).text().replace("barbel", 'mpara');
});
$(".text_div").text(function() {
return $(this).text().replace("some", "red");
});
You have a few issues here:
Use html(), not text(), to insert HTML in to the DOM.
Be careful with your quotes as you're causing a syntax error by mis-matching them.
Use the second argument of the handler function to receive the current HTML value of the element instead of creating another jQuery object by accessing the DOM again.
With all that said, try this:
$(".text_div, p").html(function(i, html) {
return html.replace('barbel', 'mpara');
});
Try this:
console.log('Before:');
console.log($('.content').html());
$(".text_div ,p").each((index, elem) => {
let newHtml = $(elem).html().replace('barbel', 'mpara');
$(elem).html(newHtml);
});
$(".text_div").each((index, elem) => {
let newHtml = $(elem).html().replace('some', "red");
$(elem).html(newHtml);
});
console.log('\n\nAfter:');
console.log($('.content').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div class="content">
<div class="text_div">This is barbel</div>
<p class="tag_p">That is barbel again</p>
<div class="text_div">Some some</div>
</div>

How to get attribute value from HTML tags

I'm trying to get the value from the HTML tag. Not the text itself, but the attribute value. What am I doing wrong?
$('label').click(function() {
$('p').text(($(this).val()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label value="hello">click</label>
<p></p>
labels don't have values, input and other form elements can have values. So in your case it is jQuery's attr function, to receive attribute values. And there is no need of the additional brackets around this getter.
$('label').click(function() {
$('p').text($(this).attr("value"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label value="hello">click</label>
<p></p>
Use data-* it allows you to use any arbitrary string. ex. data-value="hello". This is valid and universal on on any element AFAIK. The jQuery method to use is .data()
$('label').click(function() {
$('p').text($(this).data('value'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label data-value="hello">click</label>
<p></p>
You may do like this in pure JS;
var lab = document.getElementsByTagName("label")[0],
pel = document.getElementsByTagName("p")[0];
lab.onclick = e => pel.textContent = e.currentTarget.getAttribute("value");
<label value="hello">click</label>
<p></p>
$('label').click(function() {
var value = $(this).attr('value');
});
Also, I don't think value is a valid attribute on a label element.
Without jQuery...
Array.from(document.querySelectorAll('label')).forEach((label) => {
label.addEventListener('click', () => {
let value = label.getAttribute('value');
});
});

how to get value of an element using getElementById and getElementsByTagName together

I am trying to prettyprint the value of <pre> element for which I will be getting either xml or JSON as string, so I am trying to get the value first and then test if it is xml or json and call respective prettyprint methods here is my code ...
function showData(attName) {
var attData = document.getElementById(attName).getElementsByTagName('pre')[0];
alert(attData);
// once I get the value would like to test whether it is xml or json
//if (attData contains xml test condition )
prettyPrint.xml(attData);
else prettyPrint.json(attData);
document.getElementById('Details').style.display='none';
document.getElementById(attName).style.display='block';
}
So the showData will be called whenever I click on View link in the below code ..
<div id="Details" class="body">
View
</div>
<div id="${attachmentName}" style="display:none; margin-left:60px; margin-top:5px;position:absolute;background-color:#F8F8F8;padding:10px" >
<h1>${attachmentName}:${attachmentId}</h1>
<h5 style="color: #FF0066;"> [X Close] </h5> <br/>
<pre class="prettyprint">${attachmentData}</pre>
</div>
In alert I am getting [object HTMLPreElement] but not sure how to make it to string, so I have also tried ...
var objectHTMLCollection = document.getElementById(attName).getElementsByTagName('pre')[0],
string = [].map.call( objectHTMLCollection, function(node){
return node.textContent || node.innerText || "";
}).join("");
alert (objectHTMLCollection);
But still getting as HTMLPreElement...
I have tried the JQuery jQuery('#'+attName).find('.prettyprint').data(); but got the result as [object Object] .
I don't have much exposure in the JavaScript,may be I am not doing it in right way. It would be great if anyone can help on this.
Add .innerHTML - should work, get rid of the complicated mapping functions that are meant to work with multiple <pre> tags at once.
var attData = document.getElementById(attName).getElementsByTagName('pre')[0].innerHTML;
alert(attData);
If you're using jQuery:
var text = $("#" + attName + " pre:first").text();
That gets you the text content of the element.
Your last js snippet is close, but you're calling map on a non-array object, and passing the wrong var to alert(). To find all 'pre' elements:
var objectHTMLCollection = document.getElementsByTagName('pre');
var str = [].map.call( objectHTMLCollection, function(node){
return node.textContent || node.innerText || "";
}).join("");
alert (str);
If you are actually only looking for one 'pre' element:
var htmlObject = document.getElementById(attName);
var str = htmlObject.textContent || htmlObject.innerText || "";
alert (str);
Remember, an element's id is unique, so there's no point in querying by id, and tag name.

How to set what user types in textarea as a javascript variable?

Hi so I have a HTML textarea. I want what the user types in it to be displayed on the screen and also stored in a variable. I have the displaying part but I can't figure out how to store it as a a variable.
The html
<textarea id="input" maxlength="50" name="Text" placeholder="Max. 50 characters"></textarea>
The javascript
$('#input').keyup(function() {
$('#text').html($(this).val());
var yourText = this.val();
});
Firstly, you should use change or input instead of keyup. Not everyone uses a keyboard!
Second, only jQuery objects have a val() method. Using this you are referring to the <textarea> element which does not:
$('#input').on("input", function() {
var yourText = $(this).val(); // Only jQuery objects have a .val()
$('#text').html(yourText); // Pass your variable in here
});
jsFiddle Demo
$('#input').keyup(function() {
$('#text').html($(this).val());
var yourText = this.val();
});
Should be
$('#input').keyup(function() {
$('#input').html($(this).val());
var yourText = $(this).val();
});
You gave #text as an id, but the id name of the input is #input
You forget the javascript closure $ on this. Use the code below
<textarea id="input" maxlength="50" name="Text" placeholder="Max. 50 characters"></textarea>
<div id="text1"></div>
<script>
$('#input').keyup(function() {
$('#text').html($(this).val());
var yourText = $(this).val();
$("#text1").html(yourText);
});
</script>
JSFIDDLE:http://jsfiddle.net/7tfs93o2/
Hope this helps you
You are doing var yourText = this.val(); but since you are using JQuery there, .val() is a JQuery method, this should also be wrapped with the JQuery layer like this:
var yourText = $(this).val();

Javascript handle 2 data attribute

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?

Categories

Resources