JavaScript onclick return - javascript

I am new to JavaScript and I'm still figuring things out.
I already searched the web for this but I'm not quite sure what keywords should I use. I am creating some program with a random number using html and JS.
So in my javascript (inside the tag)
I have something like:
var x;
function initRandom() { // I run this function at loading time (i.e: <body onload="initRandom();">)
x = Math.random();
}
function checkGuessedNumber() { // this just checks if the number guessed by the user is == to x and displays "correct" in a div if it is correct otherwise "incorrect"
}
So the main problems I am encountering is that
The html elements gets reset after submit. For example, the text fields becomes blank, the things I displayed in a div becomes blank. It just shows for a short period of time then gets reset
After that, the generated number becomes a different number I think the html page loads once more every time I click submit. And I don't like that to happen.
What I am having confusions on is the return statement on the onClick() attribute and how is it different on without return. See examples below:
CODE1:
<form onsubmit="return checkGuessedNumber();">
<input type="text"> // input for the number
<input type="submit"> // click if already sure of input number above
</form>
CODE2:
<form onsubmit="checkGuessedNumber();"> // notice no return here
<input type="text">
<input type="submit">
</form>
And finally if I'll just gonna put the checkGuessedNumber on <input type="submit" onclick="checkGuessedNumber();"> OR having a return before that.

Here's a live demo (click) of everything in this post.
First, don't use inline js (js functions in your html, like onclick). Read some of these results: Why is inline js bad?
Just for completeness, I'll explain how it works anyway:
This disables the submit nature of the button.
<input type="submit" onclick="return false;">
Now, if you want to use a function, you still need to produce the above result, so:
<input type="submit" onclick="return foo()">
and foo will have to return false, so that return foo() is the same as return false:
function foo() {
//do what you need to do;
return false;
}
I'll update this in a moment explaining the best practice, NOT using inline js.
The best element for a "button" is <button>, so I recommend that.
<button id="my-btn">Click Me!</button>
I gave it an id so that we can easily identify it in javascript. There are plenty of other ways to get element references, but that's another topic. Now, in javascript:
//get the element reference
var myBtn = document.getElementById('my-btn');
//this will make the button call function "foo" when it is clicked.
myBtn.addEventListener('click', foo);
function foo(event) {
//do whatever you want
}
If you assign an event listener to an element that has a default behavior, you can prevent the default behavior like this:
//the "event" object is automatically passed to the event handler
function foo(event) {
event.preventDefault();
//do what you want here
}

Related

Why wont this display the value?

I want to use a value from a HTMl input but i cant make it into a variabel. Im a beginner at this so maybe it will be pretty obvious to you but i couldnt find anything on the internet that helped me with my problem.
script.js:
function getInputValue(){
var inputVal = document.getElementById("numberIn").value;
return inputVal;
}
document.getElementById('numberOut').innerHTML = getInputValue();
index.html:
<input type="text" placeholder="Dezimalzahl hier eingeben" id="numberIn">
<button type="button" onclick="getInputValue();">Convertieren</button>
<p id="numberOut"></p>
<script src="script.js"></script>
The reason it doesn't work for you is because the line document.getElementById('numberOut').innerHTML = getInputValue(); gets ran only once, when the input is empty. Your button's onclick only returns the value from the input, but it doesn't re-set it into numberOut.
Please look at my example, I took the same exact line and put it into a function that a button executes, and it seems to work perfectly!
function getInputValue() {
const inputValue = document.getElementById("myInput").value;
return inputValue;
}
function showValue() {
document.getElementById("result").innerHTML = getInputValue()
}
<input type="text" id="myInput"/>
<div id="result"></div>
<button onclick="showValue()">Click Me!</button>
Your idea is
When I click on the button, that's what should happen:
Read the value for an input element from the DOM.
Assign that value to another element.
but, in your implementation you did
When I click on the button:
Read the value.
Return it.
Believe me, that's what your implementation is saying.
If we came to the last step
document.getElementById('numberOut').innerHTML = getInputValue();
He's calling you, "Hey, why you are putting me outside the function, we did not agree like that".
So, that is the first correction
Let deal with the assignment function and place it inside the function.
The second, and after placed the assignment function in his reserved place ... the function now has the full steps
Read the value.
... ... ...
Assign it to the other element directly :), there is nothing that my function should return.
And, now!
Should I write the final getInputValue() function, or I let it to you?
Greetings ;)

Returning text into an input text box from another page on my domain using JavaScript

I'm trying to return the text from another page on my domain into an input text box. I can return the text inside a div (DivThisPage) but can't seem to get the text from the div I've loaded in to the text input field (txtValue).
function getValue() {
$("#DivThisPage").load("http://another-page-on-my-site #DivTheOtherPage"); //This is working and I see "test" on this page.
var myVal = $('#DivThisPage').val(); //I've tried both DivThisPage and DivTheOtherPage but get nothing
$("#txtValue").val(myVal);
}
Here is the HTML on this page:
<button onclick="getValue()">Get Value</button>
<div id="DivThisPage"></div>
<input type="text" id="txtValue" name="txtValue" />
The html from another page on my site:
<div id="DivTheOtherPage">test</div>
However, when I inspect the elements on the page after executing I see:
<div id="DivThisPage">
<div id="DivTheOtherPage">test</div>
</div>
But when I debug the script myVal is always null.
You have two issues here. Firstly, div elements do not have a value attribute so the val() method doesn't work for them. Assuming from the context of the question you want to get the text within the element, use html() or text().
Secondly, the AJAX call used by load() under the hood is asynchronous. This means that you will need to use the callback argument in order to read the data from the DOM after it has been updated.
<button>Get Value</button>
<div id="DivThisPage"></div>
<input type="text" id="txtValue" name="txtValue" />
jQuery(function($) {
$('button').on('click', function() {
$("#DivThisPage").load("/relative-path #DivTheOtherPage", function() {
var myVal = $('#DivTheOtherPage').text();
$("#txtValue").val(myVal);
});
});
});
Also note that use of an unobtrusive event handler here. Inline event attribute are now considered bad practice (as they tie the HTML and JS logic too tightly) and should be avoided where possible.
In addition, if you're making a call to a location on your own site, use a relative link.
Uses this:
function getValue() {
$("#DivThisPage").load("http://another-page-on-my-site #DivTheOtherPage", function(response, status, xhr){
var myVal = $('#DivThisPage').val();
$("#txtValue").val(myVal);
});
}

independently working div in Jquery

I am trying to make an independently working div which has a form inside of it.
I use jquery to calculate the price of a product depending of the user's selections in the form. However the user is able to add multiple items in his 'cart' so the form is duplicated to another div. The problem is that the calculation pattern can't separate these two divs and the calculation will be incorrect. The form is also interactive so it will be generated by the user's input. This is really complex set and renaming every variable by the 'product number' doesn't sound really efficient to me.
I'm kind of stuck here and i don't really know how to solve this problem. I had an idea that what if I put an iframe inside of the div and load my form and its calculation script inside of it, and then use post command to transfer the price of the product to the 'main page' to calculate the total price of all of the products the user wanted.
However it seems that jQuery scripts doesn't work independently inside of these iframes, they still have connection so they broke each other.
i will appreciate any kind of suggestions and help to solve this matter, thank you!
here's the code so far
Heres the body
var productNumber = 1;
<div id="div_structure">
</div>
<button id="newProduct" >Add new product</button><br \>
add new item
<!-- language: lang-javascript -->
$('#newProduct').click(function ()
{
$('<div id="productNo'+productNumber+'">')
.appendTo('#div_structure')
.html('<label onclick="$(\'#div_productNo'+productNumber+'\').slideToggle()">Product '+productNumber +' </label>'+
'<button onclick="$(\'#product'+productNumber+'\').remove()">Remove</button>');
$('<div id="div_product'+productNumber+'" style="display: none;">').appendTo('#product'+productNumber+'');
$('<iframe src="productform.html" seamless frameborder="0" crolling="no" height="600" width="1000">').appendTo('#div_product'+productNumber+'');
productNumber++;
});
it also has a function that allows the user to remove the inserted div.
Here's just few lines from the productform
$(document).ready(function()
{
$('#productCalculation').change(function ()
{
shape = $('input[name=productShape]:checked', '#productCalculation').val();
alert(shape);
});
});
<form id="productCalculation">
<div id="div_productShape" class="product1">
<h1>Select the shape of the product</h1>
<input type="radio" name="productShape" value="r1">R1</input><br \>
<input type="radio" name="productShape" value="r2">R2</input><br \>
<input type="radio" name="productShape" value="r3">R3</input><br \>
</div>
.
.
.
</form>
I translated all of the variables so they may not function correctly since i didn't test the translated version. So the problem is, if i try to make selections in the second generated div it wont even alert() the selected variable
There are two problems with this code: You say somewhere "I translated all of the variables so they may not function correctly since i didn't test the translated version. So the problem is, if i try to make selections in the second generated div it wont even alert() the selected variable". This is because event handlers are attached to elements that are in the DOM at that specific moment. To get it to work for all elements, use event delegation:
$(document).ready(function()
{
$(document).on( 'change', '#productCalculation', function ()
{
shape = $('input[name=productShape]:checked', '#productCalculation').val();
alert(shape);
});
});
Your other question is "My question in a nutshell: Is there a way to restrict jquery to function only in certain div even though i use the same variable names in the second div ". You can use the this variable to access the element the click was invoked on. From this element you can traverse the DOM if needed, for example with .parent().
$('div').on( 'change', function( e ) {
console.log( $(this).val() );
} );

adjusting dynamic form to work with multiple sections

I have a script which dynamically adds rows to a form with default values:
$(document).ready(function() {
var defaults = {
'name[]': 'Name',
'email[]': 'Email',
'organisation[]': 'Organisation',
'position[]': 'Position'
};
var setDefaults = function(inputElements, removeDefault)
{
$(inputElements).each(function() {
if (removeDefault)
{
if ($(this).data('isDefault'))
{
$(this).val('')
.removeData('isDefault')
.removeClass('default_value');
}
}
else
{
var d = defaults[this.name];
if (d && d.length)
{
this.value = d;
$(this).data('isDefault', true)
.addClass('default_value');
}
}
});
};
setDefaults(jQuery('form[name=booking] input'));
$(".add").click(function() {
var x = $("form > p:first-child").clone(true).insertBefore("form > p:last-child");
setDefaults(x.find('input'));
return false;
});
$(".remove").click(function() {
$(this).parent().remove();
});
// Toggles
$('form[name=booking]').delegate('input', {
'focus': function() {
setDefaults(this, true);
},
'blur': function() {
if (!this.value.length) setDefaults(this);
}
});
});
For the following form:
<form method="post" name="booking" action="bookingengine.php">
<p><input type="text" name="name[]">
<input type="text" name="email[]">
<input type="text" name="organisation[]">
<input type="text" name="position[]">
<span class="remove">Remove</span></p>
<p><span class="add">Add person</span><br /><br /><input type="submit" name="submit" id="submit" value="Submit" class="submit-button" /></p>
</form>
I would now like to split the form into 2 sections, each of which can have rows added dynamically to it. The second section would only have spaces for name and email, so the form as a whole, before any additional rows are added, would look something like this:
But I'm not sure how to achieve this. Either I would create a separate form with a seperate script, and then would need to know how to submit the information from both forms together, or I would just have one form but would then need to work out how to add rows dynamically to each section.
Could someone help with this?
Thanks,
Nick
I've implemented this in a fully functional example here.
I cleaned up your code a little bit, but it's basically the same. The main addition is that I wrapped the inputs in a fieldset element (you could use a div just as well, but fieldset is the semantically correct element for grouping related input fields). Your 4-input section lives in one fieldset, and your 2-input section lives in another; the "Add Person" handler looks for the parent fieldset, clones the first child, and adds it into that fieldset. Conveniently, in your use case the defaults for the first fieldset are the same as those for the second fieldset, but it would be easy enough to set up multiple sets of defaults and pass them into the setDefaults function.
A few other changes to the code:
I split your setDefaults function into two different functions, setDefaults and removeDefaults - you weren't gaining anything by making them a single function, and splitting them makes the code more legible.
I used .delegate to assign the "Remove" handler - otherwise the "Remove" button wouldn't work for new input sets. I also created the "Remove" button with jQuery, rather than cloning it, because I assumed that it wouldn't make sense to include it for the first input set.
I used jQuery in a couple of places where you were using raw Javascript (e.g. getting and setting input values). I generally assume that jQuery is more reliable for cross-browser DOM access and manipulation, so if you're loading the library already there's rarely any point not using it for all but the simplest DOM functions.
I removed your .data calls, since you can get the same information by inspecting the class, and it's generally better to reduce complexity. It's possible that .hasClass('test') is slightly slower than .data('test'), but I don't think it should make any difference here.
Create one form. Put two divs inside of it. Have your script add/remove form elements to the appropriate div.
When you submit the form it should automatically submit all of the form elements in both divs since the divs are contained in the form.

Javascript for mobile HTML form

I am having some problems with Javascript :(
This is an HTML form for a mobile webpage. To save space I put the names of the text fields inside the boxes. The name disappears when you focus on the box, but I am not able to make it reappear if the user didn't write anything.
Here is the Script (in head tag):
<script type="text/javascript"> resetDefault();{if (this.value.length==0); this.value="default";} </script>
Here is the HTML code:
<input onfocus="this.value=''" onblur="resetDefault()" name="nom" type="text" value="Nom complet" default="Nom complet"/><br><input onfocus="this.value=''" onblur="resetDefault()"name="courriel" type="text" value="Courriel" default="Courriel"/><br>
I keep getting a "resetDefault is not defined" error. I don't know if default is an accepted attribute for input, but I can't set it to "value" because value becomes 0 once someone has focused on the text field, right?
There are several problems with your javascript code. First, it is not syntactically correct. You should first change this code
resetDefault();
{if (this.value.length==0);
this.value="default";}
so that it has valid syntax, like this:
function resetDefault(){
if(this.value.length == 0){
this.value = "default";
}
}
The second problem is that this refers to the global object, instead of the DOM node you want. You need to pass in a value so it knows which input to change.
Change the onblur javascript so that it passes in a parameter to the function:
onblur="resetDefault(this);"
and change the function so it accepts a parameter:
function resetDefault(that){
if (that.value.length == 0){
that.value="default";
}
}
The third problem is that "default" will just change the value of the input box to the string, "default". I doubt that is what you want. Make the value match the default attribute you gave the input:
that.value = that.getAttribute("default");
Try it out on JSFiddle
The semicolon after resetDefault() in the script in the head needs to be removed - now it's a function call of a function that's not defined.
<script type="text/javascript">function resetDefault() { if (this.value.length==0) this.value="default";} </script>
You need to define the resetDefault() function like so:
function resetDefault() {
// Function stuff here
}

Categories

Resources