Can't get my simple JavaScript Event Handler working - javascript

I am trying to get an event handler on an HTML form. I am just trying t get the simplest thing working, but I just cannot see what I am missing.
It is part of a wider project, but since I cannot get this bit working I have reduced it down the most very basic elements 1 text field and a button to try and see what it is I am missing.
All I want to do is get some text entered and flash up message in a different area on the screen.
The user enters text into the input field (id=owner).
The plan is that when the button (id="entry") is pressed the event handler (function "entry") in the entry.js file should cause a message to display.
I don't want the form to take me to a different place it needs to stay where it is
I just want some form of text to go in the: <div id="feedback" section.
When I can get it working: I intend the create the text from the various text fields that get entered.
I Know that this is beginner stuff & I know that I have reduced this down such that it barely worth thought but I would welcome any input please & thank you.
HTML code is:
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>
<script src="entry.js"></script>
Code for entry.js is:
function entry() {
var elOwner = document.getElementById('owner');
var elMsg = document.getElementByID('feedback');
elMsg.textContent = 'hello';
}
var elEntry = document.getElementById('entry');
elEntry.onsubmit=entry;
I have tried:
Adding in a prevent default:
window.event.preventDefault();
doing this through an event Listener:
elEntry.addEventListener('submit',entry,false);
using innerHTML to post the message:
elMsg.innerHTML = "
At present all that happens is that the pushing submit reloads the page - with no indication of any text being posted anywhere.

One issue is that you have a typo, where getElementById capitalized the D at the end.
Another is that preventDefault() should be called on the form element, not the input.
Here's a working example that corrects those two mistakes.
function entry(event) {
var elOwner = document.getElementById('owner');
var elMsg = document.getElementById('feedback');
elMsg.textContent = 'hello';
event.preventDefault();
}
var entryForm = document.getElementById('entry').form;
entryForm.onsubmit = entry;
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>
I also defined a event parameter for the handler. I don't remember is window.event was ever standardized (it probably was), but I'd prefer the parameter.
Be sure to keep your developer console open so that you can get information on errors that may result from typos.

var elEntry = document.getElementById('entry');
elEntry.addEventListener("click", function(e) {
e.preventDefault();
var elMsg = document.getElementById('feedback');
elMsg.textContent = 'hello';
});
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>

Related

Javascript / HTML Question: Taking an input value from a form, and using this to send user to a URL

Thanks for reading. I'm a novice with Javscript, and have done a lot of searches to try and figure this out... (to no avail)
I'm trying to create a situation where the user inputs a single word on a form. And then when they click a submit button, the website takes the word from the input, appends it on the end of an incomplete URL, and sends them to that completed URL.
It's easy probably easy to see why this doesn't work to some of you. And also, embarassingly, I imagine a completely different approach would be best.
Your advice is appreciated.
<form action="https://vrnaut.neocities.org/" method="get">
<label for="MyForm">Enter One Word:</label>
<input type="text" id= "OneWord" name="OneWord" required>
</form>
<button onclick="myFunction()">Submit</button>
<script>
function myFunction(form) {
var GoHere = form.OneWord.value;
location.replace("https://vrnaut.neocities.org/" + GoHere);
}
</script>
Place the button inside you form
Never listen for buttons click - rather use the FORM's "submit" Event:
const EL_form = document.querySelector("#myForm");
const EL_word = document.querySelector("#OneWord");
EL_form.addEventListener("submit", (ev) => {
ev.preventDefault();
location.replace(EL_form.action + EL_word.value);
});
<form id="myForm" action="https://vrnaut.neocities.org/" method="get">
<label for="MyForm">Enter One Word:</label>
<input type="text" id="OneWord" name="OneWord" required>
<button type="submit">Submit</button>
</form>
Your approach is perfectly fine. All that's needed is a little tweaking.
<form action="https://vrnaut.neocities.org/" method="get">
<label for="MyForm">Enter One Word:</label>
<input type="text" id= "OneWord" name="OneWord" required>
<button onclick="myFunction(this.parentElement)">Submit</button>
</form>
<script>
function myFunction(form) {
var GoHere = form.getElementsByTagName("input")[0];
location.replace("https://vrnaut.neocities.org/" + GoHere.value);
}
</script>

how to append element in datalist in form using javascript

when I am removing form tag then it is working but after adding form tag from HTML it is not working. following is the code on which I am trying and what is the reason it is not working
function abc() {
var i, ele, node, parent;
var num = document.getElementById("name").value;
//num=parseInt(num);
var parent = document.getElementById("listName");
var node = document.createTextNode(num);
var ele = document.createElement("option");
ele.append(node);
parent.appendChild(ele);
//alert(num);
//num++;
document.getElementById("name").value = "";
}
<form>
<input type="input" id="name" list="listName" />
<datalist id="listName"></datalist>
<input type="submit" onclick="abc()" />
</form>
Valuing the attribute type of the input element with the submit value means submit the form.
The button documentation states indeed :
submit: The button submits the form data to the server. This is the
default if the attribute is not specified, or if the attribute is
dynamically changed to an empty or invalid value.
You don't have any form, so the current page is considered as the actual form.
As you click on the button, the function associated to onclick() is first invoked.
It adds the option in the dataList but you will never see it because the form is submitted and so you come back to the initial state of the html page.
You don't want submit a form but having a button to bind a click event to a function.
So don't use the submit type but the button type for your input :
<input type="button" value="add option" onclick="abc()" />
that matches to your requirement :
button: The button has no default behavior. It can have client-side
scripts associated with the element's events, which are triggered when
the events occur.
As a side note, your function is more complex as required and introduces too many variables that may create side effects.
This is enough :
function abc() {
var nameElement = document.getElementById("name");
var newOptionElement = document.createElement("option");
newOptionElement.textContent = nameElement.value;
var listNameElement = document.getElementById("listName");
listNameElement.appendChild(newOptionElement);
nameElement.value = "";
}
<form>
<input type="input" id="name" list="listName" />
<datalist id="listName"></datalist>
<input type="button" onclick="abc()" />
</form>
Because you used button as submit type.
If you need client side manipulation then it should not be maintain the page state (means not submit).
In your case if you will use
<input type="button" onclick="abc()" />
in place
<input type="submit" onclick="abc()" />
so it will be solve your problem.
change the html to type=button
<input type="button" onclick="abc()"/>
this works for me :
html ->
<input type="text" class='form-control' list="city" >
<datalist id="city">
</datalist>
js and jq ->
$("#city").empty(); // first empty datalist
var options=[];
options[0] = new Option('landan');
options[1] = new Option('york');
options[2] = new Option('liverPool');
$("#city").append(options);

using javascript to modify form action submits form without doing submit

I have an HTML form that I submit after changing the action with some javascript. Two different buttons can do the submit.
The interesting thing is that I was trying to debug it and inserted an alert after changing the action and before submitting the form. The form is submitted without the alert ever being displayed. To make sure it's actually performing the javascript, I added an alert before changing the action. That alert displays; the alert after changing the action does not.
<form name='FormSelect' method='post' action='Undefined'>
...
<button onclick="SubmitForm('class')">Submit</button>
...
<button onclick="SubmitForm('student')">Submit</button>
...
</form>
<script type="text/javascript">
function SubmitForm(target){
alert("Action 1: " + document.FormSelect.action);
if (target=="class") {
document.FormSelect.action = "ClassAction.php";
} else {
document.FormSelect.action = "StudentAction.php";
}
alert("Action 2: " + document.FormSelect.action);
// document.FormSelect.submit();
}
</script>
Is that the expected sequence of events?
Any button placed inside form element will cause submit action. To prevent this you can add type="button" to button elements, or make you submit callback return false;
<button type="button" onclick="SubmitForm('class')">Submit</button
see http://jsfiddle.net/yD2Uu/
As the others have already pointed out the form will be submitted anyway if you don't cancle the event. I want to suggest a JavaScript free solution to your problem.
<button formaction="ClassAction.php">Submit</button>
<button formaction="StudentAction.php">Submit</button>
It's not supported in IE < 10 though. But you can still use your function as a fallback then, just a bit more elegant ;)
function SubmitForm(button){
button.form.action = button.formaction;
}
A better solution is to give the buttons a name each and submit to Action.php and let the server get the value of the named button
$student = filter_var($_POST["student"], FILTER_SANITIZE_STRING); // php5 cleaning
when you have
<form method="post" action="Actions.php">
<input type="submit" name="student" value="John Doe" />
<input type="submit" name="student" value="Jane Doe" />
<input type="submit" name="student" value="Whatever Doe" />
</form>
Otherwise if you must
Try this
<form method='post' action='Undefined'>
...
<input type="button" value="Class" onclick="SubmitForm(this)" />
...
<input type="button" value="Student" onclick="SubmitForm(this)"/>
...
</form>
<script type="text/javascript">
var actions = {
"class":"ClassAction.php",
"student":"StudentAction.php"
}
function SubmitForm(button){
button.form.action = actions[button.value];
button.form.submit();
}
</script>
Thanks to Yauhen Vasileusky's example, I started removing code between my 1st & 2nd alerts and found that the problem seems to be the following IF statement:
if (document.FormSelect.FormName.value.substr(0,19)=="ObservationRequest_" || document.FormSelect.FormName.value=="StudentReg2013rx" || document.FormSelect.FormName.value=="Toddler Update Form v3rx")
{
document.FormSelect.action = "GenerateXDP.php";
}
When I remove it, both alerts are displayed. So the answer to my question is that changing the action does not submit the form; it was some other error in my code that made it appear as if that was the case.

Requesting specific values from an html input via Javascript

I'm trying to find a way to be able to do the following. I want to be able to get certain things from a form. In this case, I only want the "value" field and NOT the "name" field.
<div class="searchbox_team" style="margin: 0 0 10px 0; z-index: 50;">
<script type="text/javascript">
function customSearch()
{
var x = document.customSearch;
x.replace("customSearch=", "");
return x;
}
</script>
<form name="leSearch" action="/search/node/" onsubmit="return customSearch()" id="search-block-form" class="search-form">
<input type="text" name="customSearch" value="" id="edit-search-block-form-1" class="searchbox_input" title="Enter the terms you wish to search for." />
<input type="submit"/>
</form>
</div>
I have tried using the following in my function.
var x = document.customSearch.value;" but that is not working.
Can anyone shed some light on this?
It sounds like you want the value of the input for customSearch. If so then just use the following
var value = document.getElementById('edit-search-block-form-1').value;
Your input tag already has an id value hence the most efficient and simplest way to search for it is using getElementById.
hmm, so to get things from the form, you'll want to specifiy like so:
document.forms.leSearch.elements["customSearch"].value;
EDIT:
try adding a hidden field that stores the value onclick and then get that from the post or get array in your action file.. I think onsubmit call is to blame
<form name="leSearch" action="/search/node/" onclick="document.getElementById('myhiddenfield').value = customSearch()" id="search-block-form" class="search-form" method="post">
<input type="text" name="customSearch" value="" id="edit-search-block-form-1" class="searchbox_input" title="Enter the terms you wish to search for." />
<input type="hidden" value="" id="myhiddenfield" />
<input type="submit"/>
</form>
EDIT 2:
I think I figured it out.. the url was appending the field names because it was defaulting to "get" method mode.. set the action=/node/search/" and method="post"
<form method="post" action="/search/node/" onsubmit="this.action = '/search/node/' + document.getElementById('edit-search-block-form-1').value;">

E-mail form interactivity

I'm a web development student and I need some help. I have the code below; How do I make it work only when the form is submitted and not the text field is clicked. I also would like it to get and insert the textField's value in the .thanks Div. Please help me learn.
<script type="text/javascript">
$(document).ready(function(){
$(".quote").click(function(){
$(this).fadeOut(5000);
$(".thanks").fadeIn(6000);
var name = $("#name").val();
$("input").val(text);
});
});
</script>
<style type="text/css">
<!--
.thanks {
display: none;
}
-->
</style>
</head>
<body>
<form action="" method="get" id="quote" class="quote">
<p>
<label>
<input type="text" name="name" id="name" />
</label>
</p>
<p>
<label>
<input type="submit" name="button" id="button" value="Submit" />
</label>
</p>
</form>
<div class="thanks"> $("#name").val(); Thanks for contacting us, we'll get back to you as soon as posible</div><!-- End thanks -->
This is a bit rough and ready but should get you going
$(document).ready(function(){
$("#submitbutton").click(function(){
//fade out the form - provide callback function so fadein occurs once fadeout has finished
$("#theForm").fadeOut(500, function () {
//set the text of the thanks div
$("#thanks").text("Thanks for contacting us " + $("#name").val());
//fade in the new div
$("#thanks").fadeIn(600);
});
});
});
and I changed the html a bit:
<div id="theForm">
<form action="" method="get" id="quote" class="quote">
<p>
<label>
<input type="text" name="name" id="name" />
</label>
</p>
<p>
<label>
<input type="button" name="submitbutton" id="submitbutton" value="Submit" />
</label>
</p>
</form>
</div>
<div id="thanks">Thanks for contacting us, we'll get back to you as soon as posible</div><!-- End thanks -->
There are several things at issue here:
By using $('.quote').click(), you're setting a handler on any click event on any element contained within the <form>. If you want to catch only submit events, you should either set a click handler on the submit button:
// BTW, don't use an id like "button" - it'll cause confusion sooner or later
$('#button').click(function() {
// do stuff
return false; // this will keep the form from actually submitting to the server,
// which would cause a page reload and kill the rest of your JS
});
or, preferably, a submit handler on the form:
// reference by id - it's faster and won't accidentally find multiple elements
$('#quote').submit(function() {
// do stuff
return false; // as above
});
Submit handlers are better because they catch other ways of submitting a form, e.g. hitting Enter in a text input.
Also, in your hidden <div>, you're putting in Javascript in plain text, not in a <script> tag, so that's just going to be visible on the screen. You probably want a placeholder element you can reference:
<div class="thanks">Thanks for contacting us <span id="nameholder"></span>, we'll get back to you as soon as possible</div>
Then you can stick the name into the placeholder:
var name = $("#name").val();
$('#nameholder').html(name);
I don't know what you're trying to do with the line $("input").val(text); - text isn't defined here, so this doesn't really make any sense.

Categories

Resources