I'm using jQuery and I want to show FullName of a Student in popup, but I'm getting only first name, e.g. if I want to show Abc Xyz it is only showing Abc - it is taking only the first word but not the word after the space.
My code is as given below:
<a data-dialog-href="#" id="delete-#item.StudentId" href="#" data-studentName=#item.StudentName>Click Here</a>
jQuery('body').on('click', '[data-dialog-href]', function (e) {
var studentName = jQuery(this).attr('data-studentName');
alert('Student Name : ' + studentName);
}
How can I get whole string including space? Thanks in advance.
The issue is because you need to wrap the value of the attribute in your HTML in quotes, otherwise the first space reached will delimit the value. Try this:
<a data-dialog-href="#" id="delete-#item.StudentId" href="#" data-studentName="#item.StudentName">Click Here</a>
Also note that you should use the data() method to retrieve the value:
$('body').on('click', '[data-dialog-href]', e => {
var studentName = $(e.target).data('studentName');
console.log('Student Name : ' + studentName);
});
Related
I want to limit the size of a paragraph of text. The wrapper div has a dynamically created ID and the paragraph text is also dynamically inserted. The HTML and JavaScript are in the same file.
The HTML
echo"
...
<div id ='subTextWrapper$sub_id' >
<p>$submission_text</p>
</div>
...";
The JavaScript:
echo"
<script>
...
var submissionId = $sub_id;
//Limit size of a submission if too long and show a link to read more
var submissionString = $('#subTextWrapper' + submissionId).html();
if (submissionString.split(' ').length > 50) {
$('#subTextWrapper' + submissionId).html(submissionString.split(' ').slice(0, 50).join(' ')
+ ' ... '
+ `<a class='read-more' + submissionId>Read more</a>`);
}
$('a.read-more' + submissionId).click(function () {
$('#subTextWrapper' + submissionId).html(submissionString);
});
...
</script>";
In the if statement above I want to concatenate the class name read-more with ``` the variable submissionId:
`<a class='read-more' + submissionId>Read more</a>`
This doesn't seem to work. I am not an expert in JS, so any help would be appreciated. Just a note, when I remove the variable submissionId then it works, but obviously it expands all my dynamically created submissions.
You concatenation seems wrong.
What you are currently inserting is exactly what you see as string:
<a class='read-more' + submissionId>Read more</a>
and not the value of submissionId. Since you are not handling the two different delimiters correctly. You have ` enclosing the whole a element and ' enclosing the class. You are closing the class before adding the submissionId and not closing the main literal to acutally include the value of submissionId
.
You can fix it like (if submissionId is a string):
`<a class='read-more` + submissionId.trim() + `'>Read more</a>`
or
`<a class='read-more#Sub.'>Read more</a>`.replace('#Sub.', submissionId.trim())
You could also use an array to build your string to avoid the different delimiters:
//var submissionId = 1234;
var tString = [];
tString.push("<a class='read-more"); //REM: Open the class attribute and not closing it since submissionId is part of the class
tString.push(submissionId); //REM: Adding the value of submissionId
tString.push("'>Read more</a>"); //REM: Closing the class attribute
console.log(tString.join('')); //-> <a class='read-more1234'>Read more</a>
Since submissionId looks like an id/number to me, please be aware that classnames shall not start with digits.
Furthermore if you want to limit the characters of a string you could use String.prototype.substring() instead:
submissionString.substring(0, 50);
would it not work like so.
echo"
<script>
//Limit size of a submission if too long and show a link to read more
var submissionString = $('#subTextWrapper' + submissionId).html();
if (submissionString.split(' ').length > 50) {
$('#subTextWrapper' + submissionId).html(submissionString.split(' ').slice(0,
50).join(' ')
+ ' ... '
+ `<a class='read-more' + submissionId>Read more</a>`);
}
$('a.read-more'$sub_id).click(function () {
$('#subTextWrapper'$sub_id).html(submissionString);
});
...
</script>";
or you could also concatenate like so
$('a.read-more'".$sub_id.")
I want to get the user input in an input field and then display a return message on click. Code is like this:
var link = document.getElementById("link");
var getNames = document.getElementById("getName");
var lastName = getNames.value;
function showName (lastName) {
var nameIntro = "Your name is ";
function makeFullName () {
return nameIntro + " " + lastName;
}
return makeFullName ();
}
link.addEventListener('click',function(){link.innerHTML+=showName (lastName);
});
I can get this to work without this closure, but only for a given name. I want to pass the user input as argument, and this does not work.
I have checked answers, but i could not find a native JS example where the issue at hand was the same.
link to pen:
http://codepen.io/damianocel/pen/RRWzdr
You need to pass getNames.value to your function:
link.addEventListener('click', function(){
link.innerHTML += showName(getNames.value);
});
This is because you set lastName at a moment when the user has not yet input anything.
Remark
Using innerHTML is not advised, as it may go wrong when the input name has < or &, however unlikely that may be. Also adding to HTML with += is not advised.
Instead reserve a span to contain only the name:
<a id="link" href="http://www.facebook.com">
<img src="http://www.bzeaz.org/wp-content/uploads/2015/10/img-thing.jpg" width=100 height=100>
<span id="name"></span>
</a>
And in JavaScript use textContent:
var setName = document.getElementById("name");
// ...
link.addEventListener('click',function(){
setName.textContent = showName(getNames.value);
});
New to javascript, how do I fix this problem I'm having?
I want to add an a tag to a string variable that i'm creating using a function.
The whole message (eg - "Your tutor is JOHN DOE. Contact them here: CONTACT FORM") Is added to the DOM with another function (which works).
When I run the script it outputs to the browser but the second part (makeLink()) doesnt work.
This is what I get: "Your tutor is JOHN DOE. Contact them here http://www.example.com" - Instead of the URL I want word CONTACT FORM which should be a link.
How do I do this?
I tried using link() Method, which also didnt work and had similar output.
I'll only include the relevant script below, the rest works fine...
function makeMessage(){
for(i in msgArr){
stringMSG += msgArr[i];
//do not add a comma after last item
if(i < msgArr.length - 1){
stringMSG += ', ';
}
}
var highRiskmsg = "Your tutor is " + stringMSG + ". Contact them here" + makeLink();
return highRiskmsg;
}
function makeLink() {
var contactLink = document.createElement("a");//create <a> tag
contactLink.setAttribute("id", "linkC");//set id att for <a> tag
contactLink.setAttribute("href", "http://www.example.com/contact.php");//set id att for <a> tag
var contactLinkTxt = document.createTextNode("CONTACT FORM");//new text node
contactLink.appendChild(contactLinkTxt);//append text as child of <a> tag
return contactLink;
}
It seems the problem is you are returning a DOM element from your makeLink() function, and this won't concat with the string as you expect.
You need to return a valid HTML string instead, such as: <a id=".." href="..">..</a>
The quickest way to fix your code would be just to change the return for the makeLink() function as follows:
return contactLink.outerHTML;
Using outerHTML will return the HTML string for the element, rather than the element itself.
Here is a working example
As an alternative to musefan's answer, you can return an element that contains both the message and link as nodes, instead of text.
function makeMessage(){
var highRiskmsg = "Your tutor is " + msgArr.join(',') + ". Contact them here";
var span = document.createElement('span');
span.appendChild(document.createTextNode(highRiskmsg));
span.appendChild(makeLink());
return span;
}
Fiddle
I am using javascript to hide some list Items based on the user role.
I am getting the role from a list item's text(). When I am comparing the $("#activeUser").text() value against a string, it is not working.
HTML Block that I am using in my javascript to get the text() value of a list item.
<ul class="pull-right breadcrumb">
<li>Home <span class="divider">/</span> </li>
<li id="activeUser" class="active"> <?php echo ucfirst($_SESSION['sewafs_user_role']); ?> </li>
</ul>
Javascript
$(document).ready(function () {
var testRole = $("#activeUser").text();
//This block of code works
role = 'Guest';
if (role == 'Guest') {
alert("Inside if");
$("#request_history_li").hide();
$("#assign_role_li").hide();
$("#volunteer_li").hide();
$("#profile_li").show();
$("#change_password_li").show();
}
//This doesn't work why?
if (testRole == 'Guest') {
alert("Inside if");
$("#request_history_li").hide();
$("#assign_role_li").hide();
$("#volunteer_li").hide();
$("#profile_li").show();
$("#change_password_li").show();
}
});
But if I see the value of the var testRole using alert it prints Guest.
I tried converting the testRole value into string using testRole.toString() / string(testRole) method, but nothing helped.
Please let me know, where I am going wrong. Thanks.
The problem seems to be extra white-spaces in the value that you receive from $("#activeUser").text()
Solution:
You must trim the value and then use it for comparison as:
var testRole = $("#activeUser").text().trim();
OR
var testRole = $.trim($("#activeUser").text());
OR
var testRole = $("#activeUser").text();
testRole = $.trim(testRole);
Any of the above will work.
More info on jQuery trim at this link.
Whitespace test:
If you want to test if you are getting extra white spaces, then try below javascript code:
alert("-" + $("#activeUser").text() + "-");
If you get "" then you dont have whitespaces in your received value.
But if you get spaces after < or before >, then these are white spaces, that are spoiling your party.
Try trimming the string, with $.trim($("#activeUser").text());
There seem to be whitespaces in your element.
You need to trim white spaces at start and end of the string:
var testRole = $("#activeUser").text().replace(/^\s+|\s+$/g,'');
You can see why here: http://jsfiddle.net/AfUZR/1/
Demo
$(document).ready(function () {
var testRole = $("#activeUser").text().trim();
//This doesn't work why?
if (testRole == "Guest") {
alert("Inside if");
$("#request_history_li").hide();
$("#assign_role_li").hide();
$("#volunteer_li").hide();
$("#profile_li").show();
$("#change_password_li").show();
}
});
Man, first what do you must do it, it's write correct selector.
$("#request_history_li").hide();
$("#assign_role_li").hide();
you can write
$("#request_history_li, #assign_role_li").hide();
or you can add the same classes of these Elements, that is correct
<ul>
<li class="same_class 1"></li>
<li class="same_class 2"></li>
</ul>
and
$(".same_class").hide();
ok? next:
As concerns your problem, js loaded earlier than you determine the role of, use
$(document).ready(function(){
......
});
I have a html which looks roughly like this
<div id="wallPostTemplate">
<li id='comment-content--oOo-id-oOo-' class='comment-content' comment_id='-oOo-id-oOo-'>
<a class='comment-avatar' href='-oOo-link-oOo-'>
<img class='small_avatar' src='<?="../" . MESTO_ZA_UPLOAD_FAJLOVA_KORISNIKA ?>-oOo-korisnikPodaci.Slika-oOo-'></a>
-oOo-text-oOo-
</li>
</div>
Now I get the contents of the html into a sting with $('#wallPostTemplate').text() and then I want to replace dynamically the occurrences of the string -oOo-id-oOo-
with whatever data I have stored inisde a variable like -oOo-id-oOo-, -oOo-text-oOo- and so on...
Now I tried numerous ways to tackle this thing but I always end up without a solution.
Here is my latest try out. HELP pls Q_Q
var regex = new RegExp('{\-oOo\-'+index+'\-oOo\-}', "g");
post = post.replace(regex, value);
Also I tried str.replace but it does not work... It seems new lines are the problem but I have no idea how to over come this.....
edit:
To make it more simple to understand i made a example on jsfidle: http://jsfiddle.net/DdBFB/
And as you can see, you can see nothing.... it dous not work when you get the content over the html function.
If I understand your question your goal is make something like a post template that will be loaded in runtime/cliente side. So if this is really your goal you can try use the jQuery Template Plugin
Sample for your case: (don´t tested yet)
var tmlpPost = "<div id='${postId}'>" +
" <li id='comment-content-${postId}' class='comment-content' comment_id='${postId}'>" +
" <a class='comment-avatar' href='${link}'>" +
" img class='small_avatar' src='<?="../" . MESTO_ZA_UPLOAD_FAJLOVA_KORISNIKA ?>${korisnikPodaciSlika}'>" +
" </a> " +
" ${postText}" +
" </li>" +
"</div>";
$.tmpl( tmlpPost, { "postId" : "123" , "link" : "http://posturl.com", "korisnikPodaciSlika" : "something", "postText" : "Post text goes here..."}).appendTo( "#yourPostWall" );
Or using <script> not a var: See this Fiddle
<script id="tmlpPost" type="text/x-jquery-tmpl">
<div id='${postId}'>
<li id='comment-content-${postId}' class='comment-content' comment_id='${postId}'>
<a class='comment-avatar' href='${link}'>
<img class='small_avatar' src='<?="../" . MESTO_ZA_UPLOAD_FAJLOVA_KORISNIKA ?>${korisnikPodaciSlika}'>
</a>
${postText}
</li>
</div>
</script>
Now on page load:
$("#tmlpPost").tmpl( { "postId" : "123" , "link" : "http://posturl.com", "korisnikPodaciSlika" : "something", "postText" : "Post text goes here..."}).appendTo( "#output" );
Although your question is not really clear I've whipped up an example that replaces a value based on a regular expression.
var source = "-oOo-korisnikPodaci.Slika-oOo-";
var id = "korisnikPodaci.Slika";
var regex = new RegExp('\-oOo\-' + id + '\-oOo\-', "gmi");
// Match
source.replace(regex, "hello world"); // => "Hello World"
// Mismatch
source = "-oO!!!o-korisnikPodaci.Slika-oO!!!o-";
source.replace(regex, "hello world"); // => "-oO!!!o-korisnikPodaci.Slika-oO!!!o-"
ok, i figured the answer was that i set the regex flags wrong, so i went to jsfiddle and fiddled with it and you can see the answer there :)
http://jsfiddle.net/DdBFB/11/
I was missing the multi line flag Q_Q....im no good with regex even in php not to speak in js...