<form> is causing problems with my JavaScript code - javascript

I have simplified my code down to a very basic level to try to figure out why, when I add a form to any of my HTML pages that contain Javascript, the page renders twice: once with the JavaScript and once without, putting me back where I started.
Here's the simple HTML:
<form action="test.php" method="post">
<div class="section">
<fieldset>
<p id="myP"></p>
<button type='submit' name='NewClassTypes' value='NewClassTypes' id='save_button'>Save</button>
</fieldset>
</div> <!-- ends section -->
</form>
<script type="text/javascript" src="inc/js/scripts.js"></script>
So all I have is an empty paragraph and a Save button.
Then I have this Javascript code that just simple writes "Hello world!" to the paragraph element, when the Save button is clicked:
var saveButton = document.getElementById("save_button"); // Save button
var displaySomeText = function () {
var myParagraph = document.getElementById("myP");
myParagraph.textContent = "Hello World!";
}
saveButton.onclick = displaySomeText;
The problem is that when I click on the Save button, "Hello world!" displays for a brief second and then disappears.
BUT it works just fine IF I remove the FORM element.
Any ideas why this might be happening?
In the real code I need to submit data to the database, and I want to be able to use _POST to get the data I need out of all my inputs.

The reason is, after clicking on the submit button, it "submits" the form. Try changing the button's type="button" and this will not happen:
<!------vvvvvvvvvvvvv Change this!!! -->
<button type='button' name='NewClassTypes'
value='NewClassTypes' id='save_button'>Save</button>
Else, you need to give return false in your function. That would also work:
var displaySomeText = function () {
var myParagraph = document.getElementById("myP");
myParagraph.textContent = "Hello World!";
return false; // Add this!
}

The submit button type has a special functionality: it causes the form it is put in to be submitted by the browser. Putting a click handler on it does not prevent this from happening. So, the result is what is expected.
In order to not submit the form, you need to change the button type:
<input type='button' name='NewClassTypes' value='NewClassTypes' id='save_button'>Save</button>
In this case, the action property of the form doesn't make sense, as well as the method - they both are not used.

You may find it easier to use jQuery when troubleshooting issues like that.
$('#save_button').on('click', function(e){
e.preventDefault(); // don't submit the form as usual.
$('#myP').text('Hello World!');
});

Related

how do I create a javascript function that changes the html when a form submit button is pushed in django

I can easily update the html when it's not part of the form's submit or button. Or even when it's just a pure button element (rather than an input from a form). However, when I try to append a string to the class "chatGoesHere", nothing happens. The consolealso quickly reloads since the form is going to \send.
I'm happy to post my views.py and urls.py, however, I'm pretty sure the issue is inside of my html document below:
<p class="chatGoesHere" id="chatGoesHere"> 1st Item! </p>
<form action="\send\" method="post">
<input type="text" name="userMessage" />
<input type="submit" value="Send to smallest_steps bot" class="sendButt" id="sendButt" />
</form>
<script>
var btn = document.getElementById("sendButt");
btn.addEventListener("click", updateChat);
function createMenuItem(name) {
let li = document.createElement('p');
li.textContent = name;
return li;
}
const td = document.getElementById('chatGoesHere');
td.appendChild(createMenuItem("TEST2"))
function updateChat(){
const td = document.getElementById('chatGoesHere');
td.appendChild(createMenuItem("TEST3"))
}
</script>
I'd like it so that every time a user pushes the submit button of the form something gets added to the page without the page reloading.
Thank you
You need to use django with sockets.
Take a look at this walk through.
Helped me to do the same thing a few years ago!
https://channels.readthedocs.io/en/stable/tutorial/part_2.html

Javascript update text without page refresh

Just learning javascript now. I want to make a remembrance ribbon where a persons name is added via a form. I have it working but just after it happens the page refreshes and it ends up blank. Is there a quick way to achieve this without a page refresh.
https://thimbleprojects.org/mrcpower/573757
By default, when you submit a form the page will refresh. So to prevent that you can add this to the top of your submit event handler function.
function changeText(event) {
event.preventDefault();
}
try this code:
<input type="text" name="" id="yourInputId">
<button onclick="submit()">submit</button>
<div id="ribbonId"></div>
<script type="text/javascript">
function submit(){
var a = document.getElementById('yourInputId').value;
document.getElementById('ribbonId').innerHTML = a;
}

Posting Div Content in Php

I have two php pages. In the first.php page user choose orders and a div is filling with this content, no problem. And there is a confirm button to confirm these list. When the user click this button, second.php page should be opened and the contents of the div should be displayed on that page. This is my html code for the first.php div and confirm button.
<form method="post">
<div class="col-md-5" id="orderList">
<h3 align="centre">Order List</h3>
</div>
</form>
<form role="form" method="post" action="second.php">
<div id="firstConfirmButton">
<button type="submit" name="firstConfirmButton" id="firstConfirmButton" class="btn btn-primary btn-lg">Confirm</button>
</div>
</form>
This is the javascript code to post the contents to second.php. First alert is working fine but second alert is not.
$("#firstConfirmButton").click(function() {
var content = $('#orderList').html();
alert(content);
$.post("second.php", { html: content})
.done(function(data) {
alert(data);
$('#confirmForm').empty().append(data);
});
});
Second.php page has the confirForm div and I want to display the contents in this.
<div id="confirmForm"> </div>
Where is the problem?
Your button is a submit button, so if you don't cancel the default event, the form will be submitted the regular way as well.
You need to capture the event and cancel it:
$("#firstConfirmButton").click(function(e) {
var content = $('#orderList').html();
e.preventDefault();
// the rest of your code
Or in modern versions of jQuery:
$("#firstConfirmButton").on('click', function(e) {
var content = $('#orderList').html();
e.preventDefault();
// the rest of your code
You submit the form to the page second.php by using the POST method, so the data can be retrieved from the second page by using this PHP code:
var_dump($_POST);
So basically, the data is stored within the $_POST array.
Regarding your second question. You need to avoid that you submit the default form if you first need to grab a value form a Javascript. You can do that by something like that:
$("#firstConfirmButton").click(function(e) {
var data = $('#orderList').html();
e.preventDefault();
//...
}
This will avoid that your submit button submits the form without adding the desired POST data to it.

Form submission recognition: works only when a textarea is active. What do I do wrong?

I have a page where Ajax updates the feed every once in a while. Under each post there's a textarea for a reply. JQuery/Ajax can post the reply to the database without any problems when the textarea is active. I press the submit button and everything goes well.
However, if I click somewhere else on the page and the textarea becomes inactive, the submit button doesn't work anymore like it should: it submits the form to root and doesn't run the Ajax function.
Can you figure out what's wrong in my code? Thank you for your help!
There are as many forms as there are messages on the pages. The forms look like this:
<form class="reply-form">
<textarea id="reply-11123" name="comment" class="plain-editor"></textarea>
<input type="submit" class="submit" value="Reply" />
<input type="hidden" value="URL HERE" name="url" />
</form>
Ajax code (at <head>) looks like this:
<script type="text/javascript">
$(document).ready(function()
{
$('.reply-form').on('submit', function (event) {
event.preventDefault();
var $form = $(this),
message_data = $form.find('textarea[name="comment"]').val(),
url = $form.find('input[name="url"]').val();
var postData = {};
var prefix = 'data';
postData[prefix + '[message]'] = message_data;
var posting = $.post(url, postData);
});
}
</script>
If your forms are being added to the page dynamically then you need a different event binding that will attach itself to all current and future forms. The current binding you have is called a direct binding, but what you really need is a delegated binding. A different usage of on() will give you that:
$(document).on('submit', 'form.reply-form', function (event) {
...
});

YUI3 button click event is acting like a submit type instead of a button type

I am using ASP.NET MVC 3 with the Yahoo API version 3. I am trying to get my YUI3 button to redirect to another page when I click on it, this button is my cancel button. The cancel button is a plain button type, but it is being treated like a submit button. It is not redirecting to the correct page, but acting like a submit button and it kicks off my page validation like what the submit button would do.
I thought that it might be with my HTML but I did validate it. It validated 100% correct. So I then stripped down the whole page to a bare minimum but the cancel button is still working like a submit button. Here is my HTML markup:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Create2</title>
</head>
<body class="yui3-skin-sam">
<h1>Test submit</h1>
#using (Html.BeginForm())
{
<button id="SaveButton" type="submit">Save</button>
<button id="CancelButton" type="button">Cancel</button>
}
<script src="http://yui.yahooapis.com/3.6.0pr4/build/yui/yui-min.js"></script>
<script>
YUI().use('button', function (Y) {
var saveButton = new Y.Button({
srcNode: '#SaveButton'
}).render();
var cancelButton = new Y.Button({
srcNode: '#CancelButton',
on: {
'click': function (e) {
Y.config.win.location = '/Administration/Department/List';
}
}
}).render();
});
</script>
</body>
</html>
I'm not sure what I am doing wrong here? Is this maybe a bug in their API? I am testing on IE8 and on the latest version of FireFox.
UPDATE:
I forgot to mention that if these buttons are not between form tags then the redirect works fine. If I put them in form tags then the redirect does not work.
I would use a link because you are redirecting to another page. Doing it this way you wouldn't need to initialize it with javascript or register the onClick listener.
<button id="SaveButton" type="submit">Save</button>
<a id="CancelButton" href='/Administration/Department/List'>Cancel</a>
Look at this link to style your link: http://yuilibrary.com/yui/docs/button/cssbutton.html
The Y.Button widget is removing the type attribute from the Cancel button. This makes that button behave like a submit button.
There are many possible paths to make this work. I'll start from simple to complex. The first is to avoid the issue entirely and not use JavaScript at all. Just use a link:
<form action="/Administration/Department/Create2" method="post">
<button class="yui3-button">Save</button>
<a class="yui3-button" href="/Administration/Department/List">Cancel</a>
</form>
After all, all that the Button widget is doing is adding a couple of css classes to each tag and a lot of other stuff that makes more complex widgets possible. As you can see in the Styling elements with cssbutton example, even <a> tags can look like nice buttons using just the YUI css styles. If you don't have to use JavaScript, better not to use it.
A second option is to avoid the Y.Button widget and use the Y.Plugin.Button plugin. It's more lightweight in both kb and processing power. And it doesn't touch the tag attributes, so your location code will work.
YUI().use('button-plugin', function (Y) {
Y.all('button').plug(Y.Plugin.Button);
Y.one('#CancelButton').on('click', function () {
Y.config.win.location = '/Administration/Department/List';
});
});
And finally you can hack around the behavior of the Y.Button widget by preventing the default action of the button:
var cancelButton = new Y.Button({
srcNode: '#CancelButton',
on: {
'click': function (e) {
e.preventDefault();
Y.config.win.location = '/Administration/Department/List';
}
}
}).render();

Categories