Uncaught SyntaxError: Invalid or unexpected token in Html button - javascript

I create a button dynamically through javascript.
When I click on it I get the mentioned error.
The button is created like this:
var button = document.createElement("Button");
button.setAttribute("onclick", "FollowUser('" + name + "')");
button.setAttribute("id", "FollowUserButton");
When debugging it, I've tried to figure out what goes wrong when I create it. It seems to be in the part where I make the onclick event. Nothing seems odd when I set the id.
This output is returned:
button {disabled: false, form: null, formAction: "https://localhost:44398/Home/UserProfile?name=Test", …}

I'm providing my solution by presuming few things here. Please make sure to make the suitable changes in your code. The below code snippet will provide a base to the answer you want.
let name = "foo";
var button = document.createElement("BUTTON");
var text = document.createTextNode("Click me");
button.appendChild(text);
button.setAttribute("onclick", `FollowUser('${name}')`);
button.setAttribute("id", "FollowUserButton");
// Append this button to a node. For instance, append it to the body.
document.body.appendChild(button);
// Function added for testing onclick event.
function FollowUser(str) {
console.log(str);
}
I'm using template literals here to make the code more readable and less chaotic.

Related

How can I add new radio buttons without unchecking old ones? [duplicate]

I have a drop down which builds a form based of the selections that are selected. So, if someone selects 'foobar', it displays a text field, if they choose 'cheese', it displays radio buttons. The user can then enter data into these forms as they go along. The only problem is that when they add a new form element, all the rest of the information is erased. Im currently using the following to do add to the form:
document.getElementById('theform_div').innerHTML =
document.getElementById('theform_div').innerHTML + 'this is the new stuff';
How can I get it to keep whatever has be enetered in the form and also add the new field to the end?
Setting innerHTML destroys the contents of the element and rebuilds it from the HTML.
You need to build a separate DOM tree and add it by calling appendChild.
For example:
var container = document.createElement("div");
container.innerHTML = "...";
document.getElementById("theform_div").appendChild(container);
This is much easier to do using jQuery.
Step One:
Add jQuery to your headers:
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js”></script>
Step Two:
Append, don't replace, data to your DIV like this:
$("#theform_div").append("your_new_html_goes_here");
Don't use innerHTML to create the form elements. With innerHTML you're overwriting the old HTML with new HTML which will recreate all the elements. Instead you need to use the DOM to create and append the elements.
EXAMPLE
function addRadioElement()
{
var frm = document.getElementById("form_container");
var newEl = document.createElement("input");
newEl.type = "radio";
newEl.name = "foo";
newEl.value = "bar";
frm.appendChild(newEl);
}
The most correct way to do it without using a framework (like jQuery, Dojo, YUI) is:
var text = document.createTextNode('The text you want to write');
var div = document.createElement('div');
div.appendChild(text);
document.getElementById('theform_div').appendChild(div);
innerHTML, although supported by most browsers, is not standard compliant and - therefore, not guaranteed to work.
I would suggest using jQuery and its append function.

insertAdjacementHTML is not a function at <anonymous>

I am trying to place a button after an already existing button on another website. I'm trying to test it out in Chrome console, but can't figure it out.
var buttonPosition = document.getElementById('<button class="button black ">Black</button>');
This is the button that I want to place my button behind.
I then tried using the .insertAdjacementHTML function to get the button placed behind "button black"
buttonPosition.insertAdjacentHTML("afterend", "<button>Hello</button");
Then I get the error message
"Uncaught TypeError: buttonPosition.insertAdjacentHTML is not a
function
at :1:16"
This could be a rookie error, as I am very new to coding. Any help at all will be greatly appreciated. Thanks.
That's because the value of your getElementById() is not an element's ID name but an element. Try adding an ID on your button then pass its ID name to getElementById() as the value, like this:
HTML
<button class="button black" id="btn">Your button with an ID</button>
Javascript
var btn = document.getElementById('btn'); // The button itself with an ID of 'btn'
var newButton = '<button>New button</button>'; // New button to be inserted
btn.insertAdjacentHTML('afterend', newButton);
"document.getElementById" itself clarify that it want "id" of the element. As per your snippet var buttonPosition = document.getElementById('<button class="button black ">Black</button>'); I can say that you are missing the "id" but the element itself.
Solution 1::
Provide the id to the button and then try to use that id like:
<button class="button black " id="btn">Black</button>
Javascript:
var buttonPosition = document.getElementById('btn');
Solution 2::
If you are not able to provide the id, then use the class name.
var buttonPosition = document.getElementsByClassName('button')[0];
var newButton = '<button>Button</button>';
buttonPosition.insertAdjacentHTML('afterend', newButton);

Add onclick event to div in js

I'm trying to add a onclick event to a tag, but it isn't working. Can anyone tell me the correct way to add an onclick to this tag in js?
var cell = result.appendChild(document.createElement('abbr'));
cell.title = "cell number 1";
cell.className = 'chart-cell-type';
cell.addEventListener='onclick',(alert("clicked!")); //broken
As Alexis points out, your syntax is wrong. You want something like:
cell.addEventListener("click", function() {alert("clicked");})

Read more opens 1st one all the time

I've a page with about 10 short articles.
Each of them as a "Read More" button which when pressed displays hidden text
The issues I have at the moment is when I press the "Read More" on any of the 10 button it shows the 1st articles hidden content and not the selected one.
I think I need to set a unique ID to each article.. and the read more button be linked to it.. But I don't know how to set it.
I looked at this but couldn't get it working how to give a div tag a unique id using javascript
var WidgetContentHideDisplay = {
init:function() {
if ($('#content-display-hide').size() == 0) return;
$('.triggerable').click(function(e){
var element_id = $(this).attr('rel');
var element = $('#'+element_id);
element.toggle();
if (element.is(':visible')) {
$('.readmore').hide();
} else {
$('.readmore').show();
}
return false;
});
}
}
var div = documentElemnt("div");
div.id = "div_" + new Date().gettime().toString;
$(document).ready(function(){ WidgetContentHideDisplay.init(); });
OP Edit: Sorry, the original code wasn't in caps. I kept getting errors when trying to post, so I copied the code into Dreamweaver and it made it all caps for some reason.
Instead of selecting the element to toggle with an ID (i.e. $('#'+ELEMENT_ID)) you could setup a class for your item and use the class selection (e.g. $('.DETAILED-ARTICLE)') to select the child (or the brother, etc. depending how you built the HTML page).
In theory each ID should point to a single element but each class can be put to as many elements as you want.
If you're getting errors, read the errors and see what they are. Off of a quick read of your code, here are a couple things I noticed that will probably cause issues:
"documentElemnt" is misspelled, which will render it useless. Also, documentElement is a read-only property, not a function like you're using it.
toString is a function, not a property, without the parentheses (.toString()) it isn't going to function like you want it to.
Run the code, look at the errors in the console, and fix them. That's where you start.

Add to HTML form without losing current form input information in Javascript

I have a drop down which builds a form based of the selections that are selected. So, if someone selects 'foobar', it displays a text field, if they choose 'cheese', it displays radio buttons. The user can then enter data into these forms as they go along. The only problem is that when they add a new form element, all the rest of the information is erased. Im currently using the following to do add to the form:
document.getElementById('theform_div').innerHTML =
document.getElementById('theform_div').innerHTML + 'this is the new stuff';
How can I get it to keep whatever has be enetered in the form and also add the new field to the end?
Setting innerHTML destroys the contents of the element and rebuilds it from the HTML.
You need to build a separate DOM tree and add it by calling appendChild.
For example:
var container = document.createElement("div");
container.innerHTML = "...";
document.getElementById("theform_div").appendChild(container);
This is much easier to do using jQuery.
Step One:
Add jQuery to your headers:
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js”></script>
Step Two:
Append, don't replace, data to your DIV like this:
$("#theform_div").append("your_new_html_goes_here");
Don't use innerHTML to create the form elements. With innerHTML you're overwriting the old HTML with new HTML which will recreate all the elements. Instead you need to use the DOM to create and append the elements.
EXAMPLE
function addRadioElement()
{
var frm = document.getElementById("form_container");
var newEl = document.createElement("input");
newEl.type = "radio";
newEl.name = "foo";
newEl.value = "bar";
frm.appendChild(newEl);
}
The most correct way to do it without using a framework (like jQuery, Dojo, YUI) is:
var text = document.createTextNode('The text you want to write');
var div = document.createElement('div');
div.appendChild(text);
document.getElementById('theform_div').appendChild(div);
innerHTML, although supported by most browsers, is not standard compliant and - therefore, not guaranteed to work.
I would suggest using jQuery and its append function.

Categories