How can I use the attribute selector with a variable? - javascript

I need to use this form because it can handle spaces in my element ID.
$("div[id='content Module']").whatever();
However I need 'content Module' replaced with a variable?
I tried
$("div[id=" + my_var + "']").whatever();
but this did not work

You're missing a '
$("div[id=" + my_var + "']").whatever();
Should be
$("div[id='" + my_var + "']").whatever();

try this $("div[id='" + my_var + "']").whatever(); you forgot the open Apostrof

Related

How do i use onclick() method properly when passing some variable arguements i.e the arguements in this case is an ID of a Mongoose Object Document?

So I'm dynamically appending rows to a table on front-end, based on the array I get from a node.js API I wrote. The array indicates students. For each row I append and display Name, Class, Roll_No and a dynamic button whose color changes depending on the value I get from that specific student. Now for that button I use the following tag:
$('#users').append("<tr><td>" + (i + 1) + "</td><td>" + val.first_name + " " + val.last_name + "</td><td>" + val.roll_no + "</td><td>" + val.class + "</td><td><button id='tempButton' class='btn btn-danger' onclick='add_remove_student(" + val._id + ", " + val.is_linked + ")'>DELETE</button></td></tr>");
val indicates the current element of the students array, which is a mongoose object. Now I get an error whenever I click the appended button and the add_remove_student() method is not called. The error says:
uncaught SyntaxError: Invalid or unexpected token
val._id is a Mongoose ID of that particular Mongoose object and val.is_linked is a boolean value.
The onclick() in the button tag worked before I switched to node.js
I've scratched my head so many times as to what I'm doing wrong. Any help would be greatly appreciated!
The short answer: don't use onclick, or any other of the onX inline event attributes. They are outdated, lead to spaghetti code and don't follow the separation of concerns principle.
A much better way to achieve this would be to just add the relevant meta data to the element as data attributes. Then, using a single delegated event handler, you can read that metadata from the element which was clicked. Try this:
let i = 0;
let val = {
_id: "5e4780d3cfbe57182499506a",
role: ["STUDENT"],
is_active: true,
linked_students: [],
first_name: "test_fname",
last_name: "test_lname",
email: "t1#t.com",
roll_no: "537",
class: 7,
description: "im a test user mate!",
created_at: "2020-02-15T05:25:39.077Z",
updatedAt: "2020-02-15T05:25:39.077Z",
v: 0,
is_linked: true
}
$('button').on('click', function() {
$('#users').append(`<tr><td>${(++i)}</td><td>${val.first_name} ${val.last_name}</td><td>${val.roll_no}</td><td>${val.class}</td><td><button class="delete btn btn-danger" data-id="${val._id}" data-linked="${val.is_linked}">DELETE</button></td></tr>`);
});
$('#users').on('click', '.delete', function() {
let $btn = $(this);
let id = $btn.data('id');
let isLinked = $btn.data('linked');
console.log(id, isLinked);
// do something with the above data...
$(this).closest('tr').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Append</button>
<table id="users"></table>
As a side note, don't use id attributes in content which will be dynamically repeated. id need to be unique in the DOM. Use class attributes instead.
If, for whatever reason, you absolutely had to use an inline event attribute you need to fix your quotes so that they match, and you also need to escape the quotes you use in the onclick value so they don't interfere with the outer string:
$('#users').append('<tr><td>' + (i + 1) + '</td><td>' + val.first_name + ' ' + val.last_name + '</td><td>' + val.roll_no + '</td><td>' + val.class + '</td><td><button id="tempButton" class="btn btn-danger" onclick="add_remove_student(\"' + val._id + '\", \"' + val.is_linked + '\")">DELETE</button></td></tr>');
Okay so I've wrecked my brain for 24 hrs to solve this and after understanding how escape quotes characters work i've finally solved it with the following code:
$('#users').append(`<tr><td>` + (i + 1) + `</td><td>` + val.first_name + ` ` + val.last_name + `</td><td>` + val.roll_no + `</td><td>` + val.class + `</td><td><button id="tempButton" class="btn btn-danger" onclick='add_remove_student(\"` + val._id + `\",\"` + val.is_linked + `\")'>DELETE</button></td><tr>`);
Thank You ^^
This is the issue of mixing of quotes please re verify the quotes on the function calling in jquery. Plus please made an id of the element dynamic.

Can't define a variable in html

Guys I can't define variable in html .. Here is my code below:-
sb.appendHtmlConstant("<div id='Button +"i"' class=\"" + getClass(c.getIndex()) + "\">");
Here I can't define "i" to be a variable .. Any help please ??
Thanks a lot
You need to add a + before and after it.
sb.appendHtmlConstant("<div id='Button "+i+"' class=\"" + getClass(c.getIndex()) + "\">");
Adding variable to strings in java works like this:
String variable = "the variable string";
And we want to add it so that we get:
"We want to add _the variable string_ to here"
So we'll use:
String result = "We want to add _"+ variable +"_ to here";
^/*This and ^this are important*/
i should be out of the main quotes I think, as below:
sb.appendHtmlConstant("<div id='Button" + i + "' class=\"" + getClass(c.getIndex()) + "\">");

How to add an ID value to a div append

I have a "fault-counter" that stores a value of all incorrect answers. It starts at 0 and goes up one for every wrong answer.
I'm looking to have the results screen show the amount of faults you've made. So if the div #fault-counter has a value of 3, the end text will say "Sorry, you've made 3 faults!"
This is the code I've tried, but it doesn't seem to work. Any ideas on how to do this?
var faultcounter = $('#fault-counter');
$('#slickQuiz').prepend('<h1>Sorry, you have ' + $('#fault-counter') + ' faults!</h1>');
EDIT:
The HTML for the 'fault-counter' looks like this:
<div id="fault-display">
<div id="fault-counter">0</div>
<h3>FAULTS</h3>
</div>
And the jQuery being used to increase the value for every wrong answer is this:
$(".failQuestion").click(function(){
$('#fault-counter').html(function(i, val) { return val*1+1 });
});
Try this, as your fault-counter is a div than .text() should suffice.
$('#slickQuiz').prepend('<h1>Sorry, you have ' + $('#fault-counter').text() + ' faults!</h1>');
var faultcounter = $('#fault-counter').val();
$('#slickQuiz').prepend('<h1>Sorry, you have ' + faultcounter + ' faults!</h1>');
You'll have to grab the value from #fault-counter using .val() and then append the variable, instead of the jQuery selector to the #slickQuiz.
That being said, i'm assuming you're using an input or select for #fault-counter. Otherwise .text() would be sufficient
i think there is a problem :
var faultcounter = $('#fault-counter');
if $('#fault-counter') is a input control then use "VAL()" :
$('#slickQuiz').prepend('<h1>Sorry, you have ' + $('#fault-counter').val() + ' faults!</h1>');
OR
if $('#fault-counter') is a DIV control then use "html()" :
$('#slickQuiz').prepend('<h1>Sorry, you have ' + $('#fault-counter').html() + ' faults!</h1>');
var faultcounter = $('#fault-counter').text();
$('#slickQuiz').prepend('<h1>Sorry, you have ' + faultcounter + ' faults!</h1>');
This is what you want to use because you mentioned that #fault-counter is a div. If that's so then you'll want to use the .text method. If it's an input or textarea then use the .val method.

How do you document.writeln() a hyperlink?

Very simply question I can't seem to find solved here.
How can I use javascript to print a hyperlink? I'm very beginner with JavaScript and I need something like the following to work:
document.writeln("" + flaggedKCSarticles.flag_object[i].feedback_text + "");
1) Escape the internal quotes by adding a backslash:
document.writeln("<a href=\"javascript:toggleDummy1();\">" +
flaggedKCSarticles.flag_object[i].feedback_text + "</a>");
OR
2) Use single quotes:
document.writeln('<a href="javascript:toggleDummy1();">' +
flaggedKCSarticles.flag_object[i].feedback_text + "</a>");
Double quotes " are conflicting. Use a single quote in outermost, and double quotes to wrap href attribute.
So it may look like:
document.writeln('' + flaggedKCSarticles.flag_object[i].feedback_text + '')
You need to adjust quotes and double quotes so they doesn't conflict.
However, document.write and the like are very poor practice. You will learn soon enough that you need to append in a container rather than "brute print" into a document.
For example:
var a = document.createElement("a");
a.href = "javascript:toggleDummy1();";
// a more semantic way could be:
//
// a.onclick=function(event){
// toggleDummy1();
// }
//
a.innerText = flaggedKCSarticles.flag_object[i].feedback_text;
document.body.appendChild(a);
There is a problem in your markup, try this
document.writeln("" + flaggedKCSarticles.flag_object[i].feedback_text + "");
or
document.writeln("<a href='javascript:toggleDummy1();'>" + flaggedKCSarticles.flag_object[i].feedback_text + "</a>");
change your syntax like that,
document.writeln('' + flaggedKCSarticles.flag_object[i].feedback_text + '');
i hope this will work

jQuery append trouble with url parameter

I've been working for hours trying to get the single and double quotes nested correctly in order for this search result display to work, with having a dynamically appended "uniqueId" in part of the URL string on output.
Basically, the part of the JS code that is giving me trouble is this:
$('#results-list').append("<li rel='" + this.uniqueId + "'>" + this.dateTimeStamp + " — " + this.message + " — " + "<a class='iframeSmaller' href='commentDetails.php?uniqueId='" + this.uniqueId + "''>XXX</a>" + "</li>");
I want to have the "this.uniqueId" after the equal sign so that it generates a dynamic URL, which I then am going to link to a "details" page for that unique ID.
Can anyone please help me with the "this.uniqueId" syntax to get this correctly inserted into the URL for output?
Sorry if I am being unclear, I am learning all of this by the day :)
thanks!
ps... this does work, but it has a hardcoded uniqueID... what I want is a dynamic one based on the row, which is working as far as the "rel" part goes, just not the anchor part...
$('#results-list').append("<li rel='" + this.uniqueId + "'>" + this.dateTimeStamp + " — " + this.message + " — " + "<a class='iframeSmaller' href='commentDetails.php?uniqueId=32'>XXX</a>" + "</li>");
thanks again for any help with this syntax (or if there's a better way to go about what I'm trying to do)...
The quoting in your HTML for the anchor isn't quite right. You have this:
+ "<a class='iframeSmaller' href='commentDetails.php?uniqueId='" + this.uniqueId + "''>XXX</a>" +
I think it should be this (fix quoting on the link URL):
+ "<a class='iframeSmaller' href='commentDetails.php?uniqueId=" + this.uniqueId + "'>XXX</a>" +
You could see what's going on better if you build the string into a variable and then do a console.log() on the string of HTML you've built or look at its contents in the debugger.
Replace this part of your code:
... uniqueId='" + this.uniqueId + "''>XXX</a>" + "</li>");
for this one:
... uniqueId=" + this.uniqueId + "'>XXX</a>" + "</li>");

Categories

Resources