Am I missing a cast with querySelector('#element')? - javascript

I couldn't find identical answer to my question, so I decided to ask it by myself.
Im trying to select a HTML element with a specified ID in it.
This version works fine.
var button = document.getElementById('#submit');
function doSmth(){
console.log("clicked");
}
button.addEventListener('click', doSmth);
If I try to run the same code with querySelector:
var button = document.querySelector('#submit');
I get the following output:
Uncaught TypeError: button.addEventListener is not a function
Any ideas why same code outputs different return values?
This is the submit input field. It is part of the div container
<input id="#submit" type="submit">

Since the id have # use \\ to escape it
var button = document.querySelector('#\\#submit');
function doSmth() {
console.log("clicked");
}
button.addEventListener('click', doSmth);
<input id="#submit" type="submit">

Related

Button in JavaScript is not working as expected

An error message appeared after adding my button which calls a function in JavaScript. I cannot find the problem.
Sorry for the faults. I am French and I'm using Google Translate.
Here is the part of the code in question:
document.getElementById("jouer").onclick = start();
document.getElementById("jouer").onclick = function () { alert('defis[0]'); };
<input id= "jouer " type="button" value="jouer" click="start()"/>;
And the error message is:
Uncaught SyntaxError: Unexpected token '<'
It seems like you are trying to run both JS and HTML in one file.
To get it to work, you need to create a separate file with HTML stuff and use
<script src="your-js-file.js"></script> in the HTML file for the browser to be able to run JS.
function start() {
alert('i am working')
};
document.getElementById('jouer2').onclick = start
<input id= "jouer " type="button" value="jouer" onclick="start()"/>;
<input id= "jouer2" type="button" value="jouer2"/>;
target.onclick = functionRef;
functionRef is a function name or a function expression. so you can try this
document.getElementById("jouer").onclick = start;
also you don't need the click attribute in the element as you are targeting the DOM element above. if you want to trigger a function directly from some element then pass onclick attribute with the function call and you won't need to target like this
document.getElementById("jouer").onclick
reference: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onclick
The only error i see is that you have a whitspace in the id selector in the input "jouer". this causes the script to not be able to grab the element. Otherwise, the error Uncaught SyntaxError: Unexpected token '<' means that you are trying to include a file (script) that it can't find.

Get Element in Div JS

I want to create an onclick function for button that is in div with id Restyled.
I tried this:
<script>
var RestyledDiv = document.querySelector("#Restyled");
var RestyledButton = x.querySelector("button");
RestyledButton.onclick = function() {
alert("button was clicked");
}​;​
</script>
But I get this error: Uncaught SyntaxError: Invalid or unexpected token
You're looking for adding an event listener to the button and you can use the querySelector to go deeper than just a single selector level.
You also had two hidden whitespace characters in your code that resulted in the syntax error you were seeing.
Note the <0x200b> characters that are shown in my editor that is configured to show whitespace characters.
var RestyledButton = document.querySelector("#Restyled button");
RestyledButton.addEventListener('click', function() {
alert("button was clicked");
});
<div id="Restyled">
<button>Click me!</button>
</div>
i tried running your code and basically there are 2 things that i would like to point out:
var RestyledDiv = document.querySelector("#Restyled");
it is not needed here, you are not using the given div.
You can directly select the button by the provided id. You can delete the dive query line whatsoever.
it seems like there was something weird in your last line of code:
}​;​
For some reason, it was not working for me, but as soon as i literally retyped the same code - it worked.
Here's how it works for me:
<script>
var RestyledButton = document.querySelector('#restyledButton');
RestyledButton.onclick = function () {
alert('button was clicked');
};
</script>

Meteor App get value of textarea in form

I am writing a little Meteor app. There is a textarea in a form, which looks like this:
<form name="comments-form">
<label for="textarea">Comment:</label><br>
<textarea cols="40" rows="10" name="comment_textarea" class="comment_textarea">Write your comment here.</textarea><br>
<button class="btn btn-success js-add-comment">add comment</button>
</form>
In my client.js I have the following code for accessing the value of the textarea:
EVENT_HANDLED = false;
Template.website_item_details.events({
"click .js-add-comment": function(event) {
var comment_text = event.target.comment_textarea.value;
if(Meteor.user()) {
Comments.insert({
created_by: Meteor.user()._id,
text: comment_text,
website_id: this._id
});
}
return EVENT_HANDLED;
}
});
However, when I click the button to add the comment, I get the following console output:
TypeError: event.target.comment_textarea is undefined
["click .js-add-comment"]()
client.js:103
Template.prototype.events/eventMap2[k]</</<()
blaze.js:3697
Template._withTemplateInstanceFunc()
blaze.js:3671
Template.prototype.events/eventMap2[k]</<()
blaze.js:3696
attached_eventMaps/</</</<()
blaze.js:2557
Blaze._withCurrentView()
blaze.js:2211
attached_eventMaps/</</<()
blaze.js:2556
HandlerRec/this.delegatedHandler</<()
blaze.js:833
jQuery.event.dispatch()
jquery.js:4690
jQuery.event.add/elemData.handle()
This seems to be basic form handling, but somehow I can't get that text in the textarea into a variable in my javascript code. I've already tried a multitude of variants of accessing it:
document.getElementsByClass()[0].value
$('.comment_textarea').get(0).val() // there should only be one such text area anyway
event.target.comment_textarea.value;
But none of those work for me, I always get that error. It's almost like the textarea was not part of my html or there is a bug in Meteor, which prevents me from accessing textareas.
I also checked whether there are other things named comment_textarea with a fulltext search on all of my projects clientside files, but there isn't any other.
Am I simply blind and overlooking something? How do I get that text?
What's more is, that although I return false, the browser still reloads the page. Could it be related to the error happening before?
You are using the click event of the button and on that event, the textarea is not available. You need to change the event into submit form. First, put the id into your form, change the button into type submit and change the code into
"submit #your-form-id": function(event) {
event.preventDefault();
var comment_text = event.target.comment_textarea.value;
.....
}
After trying even more desperate ways to access that textarea, I think I know now what's wrong:
// var comment_text = event.target.comment_textarea.value;
// var comment_text = document.getElementByName('comment_textarea').value;
// var comment_text = document.getElementByTagName('textarea')[0].value;
// var comment_text = $('textarea').get(0).val();
// var comment_text = $('textarea').get(0).text();
var comment_text = $('textarea').get(0).value; // finally working!
So it seems that when I use jQuery, I can't use the .val() function as stated in my other answers to many other questions, but for some reason I have to treat it like a normal DOM object and use the attribute value instead of the function .val().
Maybe it's specific to the jQuery version in my Meteor app?
So I will test the following:
var comment_text = $('textarea.comment_textarea').get(0).value;
...
Yes, that also works.
Also it fixes the reload issue. I guess since there was an error, it didn't even get to return false and this is why the website reloaded.

Javascript getElementById value setting getting reset on function return

I have a simple function to show / hide a div element. I have a javascript function to do that. I debugged this with Opera. The function sets the hidden value properly on the div element. I can see the div element disappear. However, when the function returns the div element reappears. The javascript function is in its own file:main.js:
function showhide(name){
var elem = document.getElementById(name) ;
if( elem.hidden == false ) {
document.getElementById(name).hidden = true ;
} else {
document.getElementById(name).hidden = false ;
}
}
The Html is:
<div class=wrap><p>
<div class=sidebar>
<FORM><input type="submit" value="Toggle" onclick="showhide('specname');"/></FORM></div>
<div class=main>main Div
<div id="specname">collapsible text</div></div></p></div>.
I have set debugging breakpoints in the javascript function showhide to see that the value is being set properly. But on function return, the value is reset.
It is probably something simple I am missing but can't seem to see it? Any ideas? Thanks!
The answers solved my problem. I was missing the fact that the submit repainted the page and I lost my changes. I changed the type=submit to type=button. And I removed the form to just an input element with type button. That worked very nicely. Thanks everyone for your help!!! I really appreciate your answers!
The following wont do anything in some browsers:
document.getElementById(name).hidden = true
change it to
document.getElementById(name).style.display = 'block' // and 'none' for the matching line
does that make it do what you need?
As others have pointed at, it is also submitting the page - either use a different element or change the function to start :
function showHide(e, name) {
e.preventDefault();
//do the toggle here
return false;
}
The problem is you are using a submit control which will submit to the server and refresh the page. You want to stop the submit or change the control type. Both of the following should work. I recommend the 2nd one.
Try this
<FORM><input type="submit" value="Toggle" onclick="showhide('specname'); return false;"/>
or this
<input type="button" value="Toggle" onclick="showhide('specname');"/>
Probably because when you click the button the form submits and it refreshes the page ?
You should not be using a form just to have a button that does something. Instead, try using
<button onClick="showhide('specname');">Toggle</button> (and get rid of the form entirely)
Try this for your showhide().
function showhide(name){
var elem = document.getElementById(name);
(elem.style.visibility == 'hidden'?elem.style.visibility = 'visible':elem.style.visibility = 'hidden');
}
OR similarly:
function showhide(name){
var elem = document.getElementById(name);
(elem.style.display== 'none'?elem.style.display= 'inline':elem.style.display= 'none');
}
Maybe try them both and see which you need.
Cheers.

Javascript for submitting form button

I want to produce buttons through Javascript that can also do the form function. Here is how i am doing but my form function does not work when i click. Please help me out on this.
External Javascript
var onef
onef="Apple"
var twof
twof="Orange"
Now this is what i am doing in HTML page
<script>
document.write("<button>")
document.write(onef)
onClick=("this.form.T4.value++;")
</script>
<script>
document.write("<button>")
document.write(twof)
onClick=("this.form.T5.value++;")
</script>
The script works right but onClick function not working.
ouldn't you have to do this:
<script>
document.write("<button ")
document.write('onClick="this.form.T4.value++;">')
document.write(onef)
document.write("</button>")
</script>
What you are doing in your original code is building the string "<button>apple" and creating a variable called onClick with a value of "this.form.T4.value++;". What I believe you need to do is build a string with the whole button tag in it, which is what the code above is doing.
I have never seen code like this before for creating a button with JavaScript. I would go with something more like this;
var onef ="Apple";
var twof ="Orange";
function createButton(context, func, text){
var button = document.createElement("input");
button.type = "button";
button.value = text;
button.onclick = func;
context.appendChild(button);
}
createButton(document.body, function(){ this.form.T4.value++; }, onef);
createButton(document.body, function(){ this.form.T5.value++; }, twof);
An example can be seen here http://jsfiddle.net/4yV4V/
This gives you some reusable code for creating the button and passing in what ever you want the onclick even to be. Also you could customise this code for other situations.

Categories

Resources