Cannot see any output on console on using onclick property? - javascript

When I type anything and then click on submit button it doesn't show anything in my console what am I missing.
<body>
<form name="fetch-movie-title" id="fetch">
<input type="text" placeholder="Enter a movie title" id="term" />
<input type="submit" onclick="showdata()" id="search" value="Find me a poster" />
</form>
<script type="text/javascript">
function showdata() {
var film = document.getElementById('term').value;
console.log(film);
}
</script>
</body>

When I run that code I get this error displayed in the console:
Uncaught SyntaxError: Unexpected token <
… because you swapped the position of the </script> and </body> tags.
Since you say you see nothing, the problem is most likely because you run the code when the submit button is clicked.
The JS will run then the form will submit and a new page will load.
Unless you configure your console to Preserve log, this will clear the console and erase any messages displayed there.
Change the configuration.

if the body tag is inside the script tag you will be getting a parser error so the function won't be defined when the click happens.
Alternatively, you aren't preventing the form submission so the page might be reloading before you get a chance to see the output.

Related

HTML form getElementById() is NULL

Disclaimer: After some research online, I did attempt something to make sure the DOM was loaded before I queried, so please check that below, maybe I didn't get it right and that's where the problem comes from.
I know similar questions have already been asked maaaaanyyyy times but my code still doesn't work as I hoped after reading similar responses and trying to adapt my code accordingly, so please help if you can!
I am currently struggling with a form in my website. I wanted to create a form so that the admin could display a message on some of the site's pages. When I wanted to get the text that I put in the form, the returned value was NULL. I then noticed that the form I had just created was in fact nested inside another form, which doesn't work. I tried bypassing the problem by deleting the sub-form and using a formaction field but I keep having a NULL return value.
(I am using Spip for my website).
Here is the base HTML code of the admin part of the website, which contains the first form
<form method="post" action="#ENV{action}" id="form1">
<div>
#ACTION_FORMULAIRE{#ENV{action}}
[(#REM) ------------------------ Alert Message ------------------------ ]
<INCLURE{fond=formulaires/configure_alert_message}>
<script>
var msg_al = document.getElementById('alert_ortho').value;
console.log(msg_al);</script> <!-- THIS DISPLAYS THE TEXT THAT I WANT-->
<p class="buttons">
[(#ENV{choix}|=={valider_seul}|non)
<input type="submit" class="submit over" title="global_update" value="global_update" />
<input type="reset" class="submit" title="global_delete" value="global_delete" />
]
<input type="submit" class="submit" title="global_update" value="global_update" />
</p>
</div>
</form>
Then, here is configure_alert_message.html. I want the message to be sent to my page edit_article/html.
<div>
<label for="name">Alert Message :</label>
<textarea type="text" id="alert_ortho" name="alert_message">Blablabla.</textarea>
</div>
<div class="button">
<button type="submit" formaction="/edit_article.html" form="form1">Save alert message</button>
</div>
<p></p>
Lastly, here is the part of my edit_article.html file which calls for the previous code (this code is also inside a form field, I don't know if that could be a problem). I added the jQuery ready() in it in order to make sure that my query happens after DOM is loaded:
<div style="padding:10px; margin:10px; border: 3px solid #A0A0A0; text-align: center;background: #FFFF00;">
<span style="color:#FF0000;"> <strong>
<script>
$(document).ready(function() {
// do stuff when DOM is ready
var msg_al = document.getElementById('alert_ortho').value;
console.log(msg_al); <!-- THIS RETURNS "Cannot read property 'value' of null"-->
}); </script>
</strong> </span> </div>
<p class='buttons'><input type='submit' name="save" class='submit' value='save_button' /></p>
Why do I, when I try to get my message through document.getElementById('alert_ortho'), keep getting null on my page? I thought by using formaction and ready() before my query I wouldn't have this problem any more. Did I do it wrong for the DOM?
Thank you!
document.getElementById() searches the DOM of the current document for an element with a given ID.
It won't find an element in a different HTML document.
When you submit a form the data in it will be passed in the request body (for a POST form) or the query string of the URL. You need to read it from there.
Note that client-side JS has no access to the request body so this will require server-side code.

onsubmit JS script does not redirect to correct location

I want to redirect when a form is submitted using the following code:
<form onsubmit="window.location.href = '/join_game';" id='info'>
<textarea id='player_name'></textarea>
<button type='submit'><p>Join Game!</button>
</form>
the starting href value: http://localhost:5000/
I want this value: http://localhost:5000/join_game
the value that I get: http://localhost:5000/?
Why do I get that last url? If I type the exact same command into my browser's dev console, it works just fine. I've tried location.replace and location.assign, neither doing anything different. I'm pretty new to using JS with HTML, so any advice is appreciated.
Instead of using javascript, why don't you just use the good ol' action attribute of the form element like so:
and quick note: you have a paragraph element inside your button but you did not close it, I'm just going to remove it since you can directly put text inside the button.
<form action='/join_game' id='info'>
<textarea id='player_name'></textarea>
<button type='submit'>Join Game!</button>
</form>
If you want to do this with javascript you need to stop the submit of the form with return false;
<form onsubmit="window.location.href='/join_game';return false;" id='info'>
<textarea id='player_name'></textarea>
<button type='submit'>Join Game!</button>
</form>
window.location.href='/join_game'; -> you change the location
return false; - here you stop the refresh of the page that would occur with the form submit
It would be great if you put name attribute for your <textarea>, and send this like #Zack VT said, throw form action. When you assign a name to <textarea>, you can access in your for example PHP file with $_POST['name'] (example: <textarea id='player_name' name='player_name'></textarea> then in PHP file you can access what user was entered in <textarea> with $_POST['player-name'])

I cant change text using javascript?

Im working on a simple commenting system for a website using the postmail API. The thing is that i want to give the user a better error when something goes wrong because postmail only changes the URL. For this is i check the URL of the page when the page loads and if that contains an error i want to change a element to that error. The only problem is that detecting it works fine and i can also create a alert with the error but the text wont change... Can anyone help me with this?
js:
<script>
function sending(){
document.getElementById("submit_form").value = 'Sending...';
};
if (window.location.href.indexOf("err") != -1){
alert("An error occured! Please make sure to check your input fields."); //this works fine
document.getElementById("ertext").innerHTML = 'Error!'; //this doesnt
};
</script>
HTML:
<form action="https://postmail.invotes.com/send"
method="post" id="email_form">
<h2>Feedback</h2>
<h4>Your Email:</h4>
<input type="text" name="subject" placeholder="aa#aa.aa" style="width: 80%;"/><br>
<h6>Your Message:</h6>
<textarea name="text" placeholder="Give some feedback" style="resize: none; width: 80%;"></textarea>
<input type="hidden" name="access_token" value="--" />
<input type="hidden" name="success_url" value="./comments.html" />
<input type="hidden" name="error_url" value="./comments.html?err=1" /><br><br>
<input id="submit_form" type="submit" value="Send" onclick="sending();" />
</form>
<p id="ertext"></p>
<br> <br>```
The Javascript code needs to be executed after the html document is loaded. As mentioned before you can achieve this by putting the script tag somewhere below all referenced elements in your DOM.
Another possibility is to put your JavaScript into a separate file "test.js" and then include it in the head of your document:
<script type="text/javascript" src="test.js" defer></script>
Using the defer attribute makes sure the script will be executed after the page finished parsing.
It depends on where you put the script. If you put it before the DOM element, document.getElementById("ertext") wouldn't find the element.
<script>
// before the DOM element
// Below line would raise TypeError: Cannot set property 'innerHTML' of null
document.getElementById('ertext').innerHTML = location.href;
</script>
<h1 id="ertext">the element</h1>
<script>
// after the DOM element
// You'd see `the element after` which indicates
// the script that is after the DOM element can find the element.
document.getElementById('ertext').innerHTML += ' after';
</script>

Get textbox value through button in popup

I am a newbie to chrome-extension/java script development and I am stuck at the following exercise.
I created a popup with a button and a textbox. I wanted to pass the textbox value to an alert when the submit button is pressed. I have the following code so far:
popup.html
<div id="popup"></div>
<form name="q">
<input name="query" id="userQuery" type="text" />
<button id="button1">Submit</button>
<!-- <input type="button" name="button" value="query" /> -->
</form>
popup.js
document.addEventListener('DOMContentLoaded', function () {
console.log(document.getElementById('userQuery'));
document.getElementById('button1').addEventListener('click', myAlert(document.getElementById('userQuery')));
});
function myAlert(query){
alert(query.value)
}
However, I get "null" as query.value so the alert comes empty.
I also noticed that when the extension is clicked for the popup, I get an alert as well, which I don't understand why, I used both 'click' and 'onclick' but I get the same issue.
Any hint or help will be much appreciated!
One way to do it:
document.getElementById('button1').addEventListener('click', function() { myAlert(document.getElementById('userQuery')); });
In your code, the expression myAlert(document.getElementById('userQuery')) is evaluated when addEventListener is called. That's why you see a blank alert when the page loads. Instead you need to pass a function, that will be executed when the click event happens.
Try this $("#userQuery").val() OR document.getElementById("userQuery").value
instead of document.getElementById('userQuery')

How do I highlight all invalid dijit.form.ValidationTextBoxes on a dijit.form.Form?

what I'm after is a form that when submitted, runs a validation check, and highlights all invalid fields and adds the tooltips.
I'm effectively looking for something like this:
dojo.forEach(dijit.byId('myForm')._invalidWidgets, function (thisWidget,index,array) {
thisWidget.displayMessage("normal invalid/empty message should go here, seems I should be calling something higher level than this");
});
but I don't want to be digging that deep, all I want to do is trigger the same sort of thing that's triggered when you tab out of an empty required field (exclamation icon and appropriate invalid/empty message). Maybe I should just try and fire the tab-out event?
Can someone point me in the right direction?
Yes, you're correct - you can get all your validation, highlighting, even focus on the first invalid field by just calling the validate() function on a dijit.form.Form element.
Here's an example where the validate() call is added to the onSubmit event:
<head>
<script type="text/javascript">
dojo.require("dojo.parser");
dojo.require("dojo.form.Form");
dojo.require("dojo.form.ValidationTextBox");
dojo.require("dojo.form.Button");
// more includes here...
</script>
</head>
<body>
<form dojoType="dijit.form.Form" action="..." method="...">
<input dojoType="dijit.form.ValidationTextBox" trim="true" regExp="..." invalidMessage="Oops...">
<!-- // more form elemts here... -->
<button type="submit" dojoType="dijit.form.Button" ...>
Submit
</button>
<script type="dojo/method" event="onSubmit">
if (!this.validate()) {
alert("Form contains invalid data. Please correct....");
return false;
}
return true;
<script>
</form>
</body>
Hope, you find it helpful.
Cheers.
Follow-up:
Here's an example of an input field that could be used to help prompt a user as to what sort of data is expected, and would alert them when validation fails:
<input type="text" id="EXT" name="EXT" value=""
maxLength="10"
dojoType="dijit.form.ValidationTextBox"
regExp="\d+?"
trim="true"
promptMessage="<p class='help'>Please your extension. (i.e. "1234")</p>"
invalidMessage="<p class='help'>The extension field should contain only numbers.</p>">
This is a declarative example. (I misspelled it in my initial response below.)
jthomas_ in #dojo on irc.freenode.net answered my question. It turns out that I wanted to be using dijit.byId('myForm').validate() which does everything I wanted in one swoop. Thanks, jthomas_!

Categories