I had developed a LOGO-like basic turtle graphics interpreter a few years back, I wan't to put it on the web (as my cousin keeps bugging me for it). Though I am quite new to HTML, Javascript coding I thought I would give it a try & take this as a learning experience.
The below code is just for the basic UI (my UI looks very ugly and I will clean it up later).
I have written a Javascript function pushCmd which is called onsubmit of the "cmd-form".
function pushCmd()
{ var cmdText = document.forms["cmd-form"]["cmd-text"].value;
var srcElement = document.getElementById("source-container");
var srcText = new String(srcElement.innerHTML);
srcText = srcText.toUpperCase();
if (srcText.indexOf("NO CODE") != 0)
{
srcText = cmdText;
}
else
{
srcText += "<br>" + cmdText;
}
srcElement.innerHTML = srcText;
}
The form is declared like below.
<div id="command-container">
<form name="cmd-form" action="" onsubmit="pushCmd()" onreset="resetSource()" method="post">
<input type="text" name="cmd-text" size="80">
<input type="submit" value="Send">
<input type="reset" value="Reset">
<input type="button" value="Run">
</form>
</div>
The pushCmd function should alter the HTML content of the div "source-container" which by default looks like below.
<div id="source-container">NO CODE</div>
After I submit the first text (say "FWD 100"). The content of the "source-container" should change to "FWD 100". Then If I submit "RT 90", the content should be "FWD 100RT 90". This is what I expect out of it.
But when I submit the text. The content of the "source-container" changes for just an instant and then again comes back to "NO CODE". Why is this happening, can anyone please point out where my mistake lies?
I tried both get & post methods but the result is the same. I cannot see any errors or warnings in the Javascript console either. I am using Google chrome Version 26.0.1410.63 if that matters (I guess not).
Please let me know if you need any further information or the full HTML source for this.
It's happening because HTML forms submit to the server by sending a new HTTP request which in your case, with the empty action attribute, is similar to refreshing the page in your browser. In order to prevent the browser from performing the default action (submitting the form) you can return false from your function, by adding return false; as a last line in it:
function pushCmd() {
var cmdText = document.forms["cmd-form"]["cmd-text"].value;
var srcElement = document.getElementById("source-container");
var srcText = srcElement.innerHTML.toUpperCase();
if (srcText.indexOf("NO CODE") !== 0)
{
srcText = cmdText;
}
else
{
srcText += "<br>" + cmdText;
}
srcElement.innerHTML = srcText;
return false;
}
Then change your HTML attribute to return the return value of your function from the onsubmit:
onsubmit="return pushCmd()"
You need to return false from pushCmd, and change the onsubmit attribute to onsubmit="return pushCmd();" otherwise the form will submit itself and refresh the page.
Also, you need to change this line:
srcText = "<br>" + cmdText;
to:
srcText += "<br>" + cmdText;
This is equivalent to:
srcText = srcText + "<br>" + cmdText;
Which means that you want to append cmdText to srcText. If you don't have +=, you basically end up overwriting srcText with just cmdText.
Your form is actually submitting to the empty action. An empty action usually ends up refreshing the current page. So your page may be refreshing so fast that it appears to be an instant change of the source-container div.
Instead of using a Submit button, try type=button and then set that button's onclick in the javascript. (Note the id="" on the Send button in the HTML)
HTML
<div id="command-container">
<form id="cmd-form" action="" onreset="resetSource()" method="get">
<input type="text" id="cmd-text" name="command" size="80" />
<input type="button" id="btnSend" value="Send" />
<input type="reset" value="Reset" />
<input type="submit" value="Run" />
</form>
</div>
<div id="source-container">NO CODE</div>
Javascript
function pushCmd()
{
var cmdText = document.forms["cmd-form"]["cmd-text"].value;
var srcElement = document.getElementById("source-container");
var srcText = new String(srcElement.innerHTML);
srcText = srcText.toUpperCase();
alert(cmdText);
if (srcText.indexOf("NO CODE") != 0)
{
srcText = cmdText;
}
else
{
srcText += "<br>" + cmdText;
}
srcElement.innerHTML = srcText;
}
document.getElementById('btnSend').onclick = pushCmd;
See this codepen as an example of this code: http://codepen.io/keithwyland/pen/scAJy
You're submitting the form, so the page is refreshing, setting it back to its original state.
Depending on what you ultimately need, one solution is to prevent the form submission. You can do this with a simple return false; at the end of your function.
function pushCmd() {
var cmdText = document.forms["cmd-form"]["cmd-text"].value;
var srcElement = document.getElementById("source-container");
var srcText = srcElement.innerHTML;
srcText = srcText.toUpperCase();
if (srcText.indexOf("NO CODE") != 0) {
srcText = cmdText;
} else {
srcText = "<br>" + cmdText;
}
srcElement.innerHTML = srcText;
return false;
}
You are probably sending the whole page to the server which will cause it to refresh and therefore you will get the same default value back.
To prevent that from happening you can try to use AJAX, which will allow you to send data to server without refreshing the whole page.
one way to prevent your page to submit to the server is to add return false; to your function.
function pushCmd()
{ var cmdText = document.forms["cmd-form"]["cmd-text"].value;
var srcElement = document.getElementById("source-container");
var srcText = new String(srcElement.innerHTML);
srcText = srcText.toUpperCase();
if (srcText.indexOf("NO CODE") != 0)
{
srcText = cmdText;
}
else
{
srcText = "<br>" + cmdText;
}
srcElement.innerHTML = srcText;
retrun false;
}
You need to return false from your onsubmit event handler to prevent the page from refreshing itself. When you push the submit button, your event handler fires but then immediately the form is submitted, which loads the page again. If you return false from an event handler, it prevents the default behavior.
function pushCmd()
{ var cmdText = document.forms["cmd-form"]["cmd-text"].value;
var srcElement = document.getElementById("source-container");
var srcText = new String(srcElement.innerHTML);
srcText = srcText.toUpperCase();
if (srcText.indexOf("NO CODE") != 0)
{
srcText = cmdText;
}
else
{
srcText = "" + cmdText;
}
srcElement.innerHTML = srcText;
return false;
}
Additionally, you'll need to return pushCmd() instead of just pushCmd() in your event handler.
Related
i've got a chat (without any design until now)
<div id="chatHtml">
<input type="text" id="input-text-chat" placeholder="Enter Text Chat">
<div id="chat-container">
<div id=chatOutput class="chat-output"></div>
</div>
</div>
Now I have a button, which calls ja javascript function to open a new window
<button type="button" v-on:click="openChat">open chat</button>
openChat: function() {
win = top.consoleRef = window.open('', 'myconsole',
'width=350,height=250' +
',menubar=0' +
',toolbar=1' +
',status=0' +
',scrollbars=1' +
',resizable=1')
chat = document.getElementById("chatHtml").innerHTML;
win.document.write(chat);
}
And last there is the code that the chat is working
document.getElementById('input-text-chat').onkeyup = function(e) {
if (e.keyCode != 13) return;
// removing trailing/leading whitespace
// this.value = this.value.replace(/^\s+|\s+$/g, '');
if (!this.value.length) return
connection.send(this.value);
console.log(connection.send);
console.log(this.value);
appendDIV(this.value);
this.value = '';
};
var chatContainer = document.querySelector('.chat-output');
function appendDIV(event) {
var div = document.createElement('div');
div.innerHTML = event.data || event;
chatContainer.insertBefore(div, chatContainer.firstChild);
div.tabIndex = 0;
div.focus();
document.getElementById('input-text-chat').focus();
win.document.write(chatContainer.innerHTML);
}
My Problem:
The chat is not working in the new window but on the "index window" it is.
Im completely new to javascript and i dont know whats the problem.
I thik its because of the ID's or sth.
Can sb help me, that i can use the chat in the new window?
Thanks :)
the input of your new page hasn't have event yet so bind it's event
just add this
openChat: function(){
win =top.consoleRef=window.open('','myconsole',
'width=350,height=250'
+',menubar=0'
+',toolbar=1'
+',status=0'
+',scrollbars=1'
+',resizable=1')
chat = document.getElementById("chatHtml").innerHTML;
win.document.write(chat);
win.document.getElementById('input-text-chat').onkeyup = function(e) {
if (e.keyCode != 13) return;
// removing trailing/leading whitespace
// this.value = this.value.replace(/^\s+|\s+$/g, '');
if (!this.value.length) return
connection.send(this.value);
console.log(connection.send);
console.log(this.value);
appendDIV(this.value);
this.value = '';
};
}
after
win.document.write(chatContainer.innerHTML);
also it's better if you put a name it that event to lessen your code
I have the following code...
var leave_page_confirm=false;
if ($(':input.common_class').val().length !== 0) {
var leave_page_confirm=true;
}
window.onbeforeunload = save_data_check;
function save_data_check()
{
if (leave_page_confirm) {
return "You have unsaved information on the page.";
}
}
I'm trying to see if any inputs on the page have value. If they don't then you can leave the page without a message. If they do, then there is a message you asking if you would like to leave the page. All of the inputs on my page have a common class.
Some information about the logic I have followed:
This code doesn't save anything, if you need to store some information just with JS, so on the client computer and this will depend on the cache, you can use the cookie(the information are temporary since rely on cookies that can be deleted, so maybe you can store the unsaved values to wait the user to submit them).
The first snippet is based on the idea that the inputs will not be cleared once you save the information(they will keep the information), this means that js checks if the user makes any change to them (can be smarter, maybe check if the value is really different from the beginning one) and set var to true/false, once the user leaves the page then var is checked.
The second script is based on the idea that the inputs are part of a form or something like this, so once it get submitted the inputs will be cleared.
if the user leaves the page the code check if the are any non-empty (saved or not) value.
To sum up:
the first checks if any change has been made to the input
the second one check if the input contains a value
I don't understand the unsaved data: unsaved data or empty values? I mean if a user save a non empty value and then clean the input?
This is what I thought: basically every time the input change it sets the saved var to false and once you hit the button save (or every other logic) it sets the value to true, otherwise once you unload the page the script check the var to see if it is true or false
HTML:
<input type='input' class='test' />
<input type='input' class='test' />
<input type='input' class='test' />
<input type='input' class='test' />
<input type='input' class='test' />
<input type='input' class='test' />
<button class='save'>Save</button>
JQUERY
var saved= true;
window.onbeforeunload = function () {
if (!saved) {
return 'Would you like to save?';
}
};
$('.test').on('input', function(){
saved=false;
});
$('.save').click(function(){
saved=true;
});
If you just need to check for the input value:
window.onbeforeunload = function () {
var saved= true;
$('.test').val(function(e,v){
//This check if the value is not empty
//if you want any kind of value use if(v)
if(v.trim()!=""){
saved=false;
return;
}
});
if(!saved)
return 'Would you like to save?';
};
You can achive this even with pure js:
window.onbeforeunload = function () {
var saved= true,
items= document.getElementsByClassName('test'),
count= items.length;
for(i=0;i<count;i++){
if(items[i].value!=""){ //if(items[i].value)
saved=false;
break;
}
};
if(!saved)
return 'Would you like to save?';
};
EDIT COOKIE PART - FIXED - WORKS
$(document).ready(function() {
var cookieVal = getCookie('formValue');
if(cookieVal){
var list=$.parseJSON(cookieVal);
$('.test').each(function(){
if($(this).attr('name') in list)
$(this).val(list[$(this).attr('name')]);
});
document.cookie = 'formValue=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
});
window.onbeforeunload = function () {
var saved= true;
$('.test').each(function(){
if($(this).val().trim()!=""){
saved=false;
return;
}
});
if(!saved){
var itemObj= new Object,
d = new Date();
d.setTime(d.getTime() + (30*24*60*60*1000));
var expires = "expires="+d.toUTCString();
$('.test').val(function(e,v){
if($(this).attr('name'))
itemObj[$(this).attr('name')]=v;
});
itemObj=JSON.stringify(itemObj);
document.cookie = 'formValue=' + itemObj + "; " + expires;
return 'Would you like to save?';
}
};
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
}
}
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
Since you are using jQuery already use each.
var leave_page_confirm = true;
$('.common_class').each(function(){
if($(this).val().length == 0)
leave_page_confirm = false
});
Also check for false if any of them are false it will always return false instead of worrying about checking every one and setting true or false. It will always be false for 1 empty.
One crude way
var leave_page_confirm=false;
$('input').each(
function(){
if($(this).val()){
leave_page_confirm = true;
}
});
try this
var changesSaved =true;
function hasPendingChanges()
{
changesSaved=$(':input.common_class').val().length == 0;
}
window.onbeforeunload = save_data_check;
function save_data_check()
{
if (!changesSaved) {
return "You have unsaved information on the page.";
}
}
I generally use change event to track any of the input has changes as,
var leave_page_confirm = false;
$(function() {
$(':input.common_class').change(function(){
leave_page_confirm = true;
if(!leave_page_confirm)
window.onbeforeunload = save_data_check;
});
});
function save_data_check(){
return "You have unsaved information on the page.";
}
I have some Javascript that adds some disclaimer text and a confirmation CheckBox, just before a submit button on a PHP/WordPress page. What I'd like to happen is the script checks for the existence of a cookie. If cookie doesn't exist (or has expired), then to add the disclaimer text, the checkbox and force the user to click the Checkbox before proceeding. But once done, a cookie is written so that the next time the script runs, if bypasses the disclaimer text, checkbox and just allows the user to hit 'submit'.
So, something like:
if cookie-exists {
// straight to submit part of the code
} else {
// show disclaimer and checkbox
// Only allow user to hit submit if checkbox is ticked
// Set the cookie with an expire of a day
}
I can see an answer on setting / reading a cookie here > How do I create and read a value from cookie?
But I'm just struggling to get it into the code snippet below.
Any pointers or help would be greatly appreciated. Thanks.
Code snippet follows:
function add_listing_select_cb()
{
?>
<script type="text/javascript">
jQuery(document).ready(function ($){
var checkbox_cont = '<br><input type="checkbox" name="I_Agree" id="I_Agree" value="I_Agree" /> <b>Disclaimer text here....</b>';
jQuery(".property-search input[type='submit']").before(checkbox_cont);
jQuery("#searchform").submit(function () {
if (!jQuery("#I_Agree").is(":checked")) {
alert("Please first agree with the terms.");
return false;
};
});
var $sel = $('#showresultsbasedonourratings'),
$opts = $sel.children();
$optsSorted = [];
$optsSorted.push($opts.eq(0));
for (var i = $opts.length - 1; i > 0; i--) {
$optsSorted.push($opts.eq(i));
};
console.log($optsSorted);
$sel.empty();
$sel.append($optsSorted);
});
</script>
<?php
}
Have you tried something similar to this?
function add_listing_select_cb()
{
?>
<script type="text/javascript">
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
jQuery(document).ready(function ($){
if (getCookie("anything")!==true){
var checkbox_cont = '<br><input type="checkbox" **required** name="I_Agree" id="I_Agree" value="I_Agree" /> <b>Disclaimer text here....</b>';
jQuery(".property-search input[type='submit']").before(checkbox_cont);
jQuery("#searchform").submit(function () {
if (!jQuery("#I_Agree").is(":checked")) {
alert("Please first agree with the terms.");
return false;
};
});
}
var $sel = $('#showresultsbasedonourratings'),
$opts = $sel.children();
$optsSorted = [];
$optsSorted.push($opts.eq(0));
for (var i = $opts.length - 1; i > 0; i--) {
$optsSorted.push($opts.eq(i));
};
console.log($optsSorted);
$sel.empty();
$sel.append($optsSorted);
});
</script>
<?php
}
<td valign="top"><center>
<textarea id="ta_in" rows="7" cols="42" onkeyup="get_ml()"></textarea><br>
<textarea id="ta_out" rows=7" cols="42"></textarea></center>
</td>
//javascript file.
function get_ml()
{
en = "|" + document.getElementById("ta_in").value;
ml = "";
n = 0;
.....
.....
.....
document.getElementById("ta_out").value = ml;
}
//i need to use addEvent instead of onkeyup
For modern browser compatibility, you would use addEventListener like this:
document.getElementById("ta_in").addEventListener("keyup", function(e) {
var en = "|" + document.getElementById("ta_in").value;
var ml = "";
var n = 0;
.....
.....
.....
document.getElementById("ta_out").value = ml;
});
Working demo: http://jsfiddle.net/jfriend00/6QMFV/
You would just run this code after your page has been loaded, by either placing the code at the end of your page (just before </body>) or by putting it in a function that you call from just before </body> or by calling this code for an event handler that listens for an event that tells you the page is loaded.
This question already has answers here:
Submit form without page reloading
(19 answers)
Closed 9 years ago.
I have a function built in JavaScript that I want to be executed after a form submit is hit. It basically changes the look of the page completely. But I need a variable from the search box to still go through to the JavaScript. At the moment it flashes and resets what was there because it reloads the page.
So I set up a return false in my function which keeps it from doing that but the variable I want doesn't get submitted through the form. Any ideas on what I should do to get it? It's okay for the page to refresh as long as the updateTable() function works and isn't reset by the page reset.
<form action="" method="get" onsubmit="return updateTable();">
<input name="search" type="text">
<input type="submit" value="Search" >
</form>
This is the updateTable function:
function updateTable() {
var photoViewer = document.getElementById('photoViewer');
var photo = document.getElementById('photo1').href;
var numOfPics = 5;
var columns = 3;
var rows = Math.ceil(numOfPics/columns);
var content="";
var count=0;
content = "<table class='photoViewer' id='photoViewer'>";
for (r = 0; r < rows; r++) {
content +="<tr>";
for (c = 0; c < columns; c++) {
count++;
if(count == numOfPics) break; // check if number of cells is equal number of pictures to stop
content +="<td><a href='"+photo+"' id='photo1'><img class='photo' src='"+photo+"' alt='Photo'></a><p>City View</p></td>";
}
content +="</tr>";
}
content += "</table>";
photoViewer.innerHTML = content;
}
You can't do this using forms the normal way. Instead, you want to use AJAX.
A sample function that will submit the data and alert the page response.
function submitForm() {
var http = new XMLHttpRequest();
http.open("POST", "<<whereverTheFormIsGoing>>", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "search=" + <<get search value>>; // probably use document.getElementById(...).value
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
You can use jQuery serialize function along with get/post as follows:
$.get('server.php?' + $('#theForm').serialize())
$.post('server.php', $('#theform').serialize())
jQuery Serialize Documentation: http://api.jquery.com/serialize/
Simple AJAX submit using jQuery:
// this is the id of the submit button
$("#submitButtonId").click(function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
I guess this is what you need. Try this .
<form action="" method="get">
<input name="search" type="text">
<input type="button" value="Search" onclick="return updateTable();">
</form>
and your javascript code is the same
function updateTable()
{
var photoViewer = document.getElementById('photoViewer');
var photo = document.getElementById('photo1').href;
var numOfPics = 5;
var columns = 3;
var rows = Math.ceil(numOfPics/columns);
var content="";
var count=0;
content = "<table class='photoViewer' id='photoViewer'>";
for (r = 0; r < rows; r++) {
content +="<tr>";
for (c = 0; c < columns; c++) {
count++;
if(count == numOfPics)break; // here is check if number of cells equal Number of Pictures to stop
content +="<td><a href='"+photo+"' id='photo1'><img class='photo' src='"+photo+"' alt='Photo'></a><p>City View</p></td>";
}
content +="</tr>";
}
content += "</table>";
photoViewer.innerHTML = content;
}
I did it a different way to what I was wanting to do...gave me the result I needed. I chose not to submit the form, rather just get the value of the text field and use it in the javascript and then reset the text field. Sorry if I bothered anyone with this question.
Basically just did this:
var search = document.getElementById('search').value;
document.getElementById('search').value = "";