Javascript Isn't Running in HTML Webpage When Inputting Data - javascript

Whenever I run the code it brings me to the webpage and everything appears fine but when I submit a value wihtin the text box, nothing happens. It just restarts the webpage with the submission and thats it. I don't get any of the alerts in the code.
My Code: CODE
I tried putting the into the head or the body and still no change. I tried changing values and changing orders but still nothing. I'm pretty certain I'm not spelling anything incorrectly because I did't get any red underlines and I looked over the code a couple times and didn't notice any misspellings. I expect to have one the three alerts to appear whenever a value is submitted on the webpage.

I'm sure you're still learning the basics, but this is something you should watch tutorials on, and maybe look at other people's code to get a better understanding of how JavaScript works.
All you need is the preventDefault() function, that can be run on an event, like submit. This is really only important in the case of forms. Here's how the preventDefault() function works:
const form = document.querySelector('form'),
responseList = document.querySelector('ul')
form.addEventListener('submit', (e) => {
e.preventDefault()
const inputs = e.target.querySelectorAll('input')
inputs.forEach(input => {
const responseOutput = document.createElement('li'),
{name, value} = input
responseOutput.innerText = `${name}: ${value}`
responseList.appendChild(responseOutput)
})
})
<form>
<input type="text" name="Anything" />
<br>
<input type="text" name="Something Else" />
<br>
<button type="submit">Submit</button>
</form>
<br>
<div>
<span>Response:</span>
<ul></ul>
</div>
I should also mention, that in your case, you should switch to using an `onsubmit` on the `` rather than an `onclick` on the ``. It will make it more clear. That is, if you don't want to use an `addEventListener()` like I use in my example.

Related

Textarea wont allow me to write into it [React]

I'm making a web app with react and in one of my functions I fetch some data from the backend and then I show it to the user by changing the value of the textarea. The problem is that I want the textarea not to be edited when the user presses a button to fetch the data from the backend but then if I click the textarea I want it to erease the data fetched and allow the user to write into itself.
This is how the code looks like in the component that contains the textarea:
<div id="text-div" onClick={this.onWrite}>
<textarea id="text" rows={13} value={this.state.value} onChange={this.handleChange}></textarea></div>
<Button onClick={this.handleRead}>Read</Button>
//functions within the code
onWrite() {
// do stuff
document.getElementById("text").setAttribute("contentEditable", true);
}
async handleRead() {
// fetches data and saves it into this.state.value
document.getElementById("text").setAttribute("contentEditable", false);
}
I've also tried using readOnly but it doesn't work either, when I call handleRead() it doesnt let the user write and shows the data (as expected) but when i call onWrite() (it would set readOnly property to false) it does not let the user write. So I cant revert what handleRead() did.
I would really appreciate some suggestions because I'm kind of a noob in React and this is my first project, sorry if I missed something.
contenteditable is an attribute added to non-editable fields like div to make them editable
You want to use readonly or disabled
I converted your example to vanilla to make it usable here
function onWrite() {
// do stuff
document.getElementById("text").removeAttribute("readonly");
}
async function handleRead() {
document.getElementById("text").value = 'test'
document.getElementById("text").setAttribute("readonly", true)
}
<div id="text-div" onclick="onWrite()">
<textarea id="text" rows="13"></textarea>
</div>
<button onclick="handleRead()">Read</button>
This might be because you have already assigned some value to your input field.
So use defaultValue instead of value
So try writing your code like this
<div id="text-div" onClick={this.onWrite}>
<textarea id="text" rows={13} defaultValue={this.state.value} onChange={this.handleChange}>
</textarea>
</div>
<Button onClick={this.handleRead}>Read</Button>
This should solve your problem.

Using a merged array in another function

Not sure exactly how to word this but hopefully you'll get my drift. I'm trying to use my If statement to merger the contents of my images array into another array, there is then a function that uses that array to do a picture slide show.
I feel that I should mention that this is a school assignment, so I'd like to not change the chgSlide function if I don't have too.
I think my problem is that when i have var myPix=[] it clears the merger. But i'm not sure really what the solution is, i've tried just doing myPix=redCarsPic but it didn't work.
Also, within the code i commented out that ways i had merged the array, i'm not sure if a certain approach is better than an other, i'm sort of partial to the jquery and would like to be able to keep that approach if i can.
Heres my script block:
function radioCheck(){
if (document.getElementById("redCars").checked){
//alert("red"); Array.prototype.push.apply(myPix,redCarsPic);
//alert("red"); myPix.push.apply(myPix, redCarsPic);
$.merge(myPix,redCarsPic)
alert(redCarsPic+" r2");
};
if (document.getElementById("blueCars").checked){
alert("blue"); myPix.push.apply(myPix, blueCarsPic);
};
if (document.getElementById("greenCars").checked){
alert("green"); myPix.push.apply(myPix, greenCarsPic);
};
}
var myPix=[];
thisPic=0;
imgCt=myPix.length-1;
alert(myPix+"mpixalt")
function chgSlide(direction){
if(document.images){
thisPic=thisPic+direction
if(thisPic>imgCt){
thisPic=0
}
if(thisPic<0){
thisPic-imgct
}
document.myPicture.src=myPix[thisPic]
}
}
var redCarsPic =["images/redCarsA.jpg","images/redCarsB.jpg","images/redCarsC.jpg","images/redCarsD.jpg","images/redCarsE.jpg"];
var blueCarsPic =["images/blueCarsA.jpg","images/blueCarsB.jpg","images/blueCarsC.jpg","images/blueCarsD.jpg","images/blueCarsE.jpg"];
var greenCarsPic =["images/greenCarsA.jpg","images/greenCarsB.jpg","images/greenCarsC.jpg","images/greenCarsD.jpg","images/greenCarsE.jpg"];
Heres the entire code if needed:
http://pastebin.com/YLtWFciE
When you press the submit button in your form, it tries to submit your form which causes the page to be reloaded, thus reinitializing all your state back to a new page which is an empty array.
You can stop the form from submitting either by changing the button to be just a normal button, not a submit button or by block the default action of the form submission.
The simplest change is to just change this:
<input type="submit" id="submitButton" value="Go!" onclick="radioCheck()"/>
to this:
<input type="button" id="submitButton" value="Go!" onclick="radioCheck()"/>
With no submit button, the form will not be submitted and the page will not reload.
Working demo: http://jsfiddle.net/jfriend00/4bx35hjy/
FYI, it is also possible to cancel the form submission in your radioCheck() function before it occurs, but since you never want to submit the form, it seems better to just not ever have a submit button in the first place.

JS Replacing form inputs with user input

I'm a novice with javascript, and am struggling with my final project for a class. We're essentially making an online quiz. It's a math quiz, and I've set up forms with text input fields for the answer, and those forms are within div containers. I'm trying to create a function that, upon clicking a submit button, will pull the value of the user's input, and use that value to replace the form as the inner html of the div. This way the answer will be committed and cannot be changed after the user submits their answer. One key step of this is that the digits of the answer are entered individually - a field for the tens column, a field for the ones. I'm trying to pull those separately, concatenate them, and then compare them with the calculated actual answer. The actual answer will replace the submit button, color coded to reflect whether the user was correct or not. Here's what I have:
var firstNumber = Math.floor((Math.random()*50)+1);
var secondNumber = Math.floor((Math.random()*50)+1);
var generate = function(){
document.getElementById("addends1").innerHTML=firstNumber;
document.getElementById("addends2").innerHTML=secondNumber;
};
var evaluate = function(){
var result = firstNumber+secondNumber;
document.getElementById("button").innerHTML=result;
var tens = document.getElementById("result10s").value;
var ones = document.getElementById("result1s").value;
var entry = tens + ones;
document.getElementById("resultContainer").innerHTML=entry;
var cO = document.getElementById("cO").value;
document.getElementById("carryOverContainer").innerHTML=cO;
var answer = parseFloat(entry);
if (answer===result) {
document.getElementbyID("resultContainer").style.color="#b2f078";
} else {
document.getElementbyID("resultContainer").style.color="#e87c73";
}
};
document.getElementById("button").onclick=evaluate();
(the first function is called in the html tag, onload for the button image)
Thanks!
Edit: My problem is just that my code isn't doing anything at all. I don't know if that has to do with how I'm calling the "evaluate" function, or the function itself. I want to replace all form fields with their entered values, and then also replace the button with the correct answer to the addition problem. Here's my html:
<body>
<div id="carryOverContainer">
<form>
<input type="text" name="carryOver" id="cO"/>
</form>
</div>
<div id="addends1" class="addends"> </div>
<div id="addends2" class="addends"> </div>
<div id="resultContainer">
<form>
<input type="text" id="result10s" class="result">
<input type="text" id="result1s" class="result">
</form>
</div>
<div id="button" onclick=evaluate();>
<img src="next.png" alt="next" onload="generate();"/>
</div>
</body>
I'm suspecting the problem may lie in how I'm trying to pull and store the values from the form fields?
As there are potentially many issues, I'll help you in steps rather than try to give you the whole solution. (It's the weekend now, so I can respond more frequently.)
The first issue is in the way you're defining and using functions. Your syntax, i.e.
var evaluate = function() {
// ...
}
defines an anonymous function assigned to the variable generate. For comparison, here's how regular functions are defined:
function evaluate() {
// ...
}
Your syntax can work if called properly, but you're calling it like a regular function:
document.getElementById("button").onclick=evaluate();
What's happening is, whereas for a regular function, the function evaluate() would get assigned to the onclick event, for an anonymous function, evaluate and () are interpreted as call the anonymous function in this variable. Therefore, evaluate() is getting called right away, instead of onclick! Here's a JSFiddle that shows how your form fields are immediately replaced.
Once you've fixed this issue, update your question and comment on my answer to grab my attention, and we'll take it from there.
By the way, if you're using Chrome, hit CtrlShiftI and go to the Console tab to see if your Javascript is throwing any issues. Firefox has a similar feature—look for developer tools in the menu.

on('submit' works when clicking the <button> but not when pressing enter on an input field

I'm using on('submit') to detect when the form was submitted, but it only works when the user clicks on the submit button.
I use a <button> tag so I can put an image inside the button. I know I could use an input with type="submit" and use CSS it with the image, but I'd like to know the alternative jQuery way.
I was thinking doing an or comparison, for example on('submit') OR when user presses enter on any of the input field, but how should I do that?
$('#form').on('submit', function (e) {
e.preventDefault();
var email = $('#email').val();
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
});
<form id="form">
<input id="email" maxlength="64" name="EmailEDIT" type="text" width="100">
<button id="submitBtn"><img height="30" src="images/fx_demo_button.png" width="74"></button>
</form>
If the user presses enter in one of the field, the form will submit. It will trigger the same event as the button does. If this does not occur, something's up in your code.
You commented that your code doesnt work, but it does: http://jsfiddle.net/B5pZ4/
All I've added was alert(1); the rest is your code from this topic
You define your function in the eventhandler, might be better to seperate that, just in case you want to use that function again (or alter it a bit and use it in two situations).
If you seperate it in your code, it'll make more sense, I also think this is the problem you're having:
http://jsfiddle.net/B5pZ4/1/
You can actually make your code work with just one line. You create the function in your eventhandler (which, in this case, should be considered bad practice!), but you never call it. Either remove the function declaration, or add this under the function:
return validateEmail( email ); // THIS IS BAD PRACTICE AS FIX!
A tip: if you're working in html5, you can use this and the browser will do validating for you:
<input type="email" />
You need to insert an invisible input type submit for this to work.

Clear default values using onsubmit

I need to clear the default values from input fields using js, but all of my attempts so far have failed to target and clear the fields. I was hoping to use onSubmit to excute a function to clear all default values (if the user has not changed them) before the form is submitted.
<form method='get' class='custom_search widget custom_search_custom_fields__search' onSubmit='clearDefaults' action='http://www.example.com' >
<input name='cs-Price-2' id='cs-Price-2' class='short_form' value='Min. Price' />
<input name='cs-Price-3' id='cs-Price-3' class='short_form' value='Max Price' />
<input type='submit' name='search' class='formbutton' value=''/>
</form>
How would you accomplish this?
Read the ids+values of all your fields when the page first loads (using something like jquery to get all "textarea", "input" and "select" tags for example)
On submit, compare the now contained values to what you stored on loading the page
Replace the ones that have not changed with empty values
If it's still unclear, describe where you're getting stuck and I'll describe more in depth.
Edit: Adding some code, using jQuery. It's only for the textarea-tag and it doesn't respond to the actual events, but hopefully it explains the idea further:
// Keep default values here
var defaults = {};
// Run something like this on load
$('textarea').each(function(i, e) {
defaults[$(e).attr('id')] = $(e).text();
});
// Run something like this before submit
$('textarea').each(function(i, e){
if (defaults[$(e).attr('id')] === $(e).text())
$(e).text('');
})
Edit: Adding some more code for more detailed help. This should be somewhat complete code (with a quality disclaimer since I'm by no means a jQuery expert) and just requires to be included on your page. Nothing else has to be done, except giving all your input tags unique ids and type="text" (but they should have that anyway):
$(document).ready(function(){
// Default values will live here
var defaults = {};
// This reads and stores all text input defaults for later use
$('input[type=text]').each(function(){
defaults[$(this).attr('id')] = $(this).text();
});
// For each of your submit buttons,
// add an event handler for the submit event
// that finds all text inputs and clears the ones not changed
$('input[type=submit]').each(function(){
$(this).submit(function(){
$('input[type=text]').each(function(){
if (defaults[$(this).attr('id')] === $(this).text())
$(this).text('');
});
});
});
});
If this still doesn't make any sense, you should read some tutorials about jQuery and/or javascript.
Note: This is currently only supported in Google Chrome and Safari. I do not expect this to be a satisfactory answer to your problem, but I think it should be noted how this problem can be tackled in HTML 5.
HTML 5 introduced the placeholder attribute, which does not get submitted unless it was replaced:
<form>
<input name="q" placeholder="Search Bookmarks and History">
<input type="submit" value="Search">
</form>
Further reading:
DiveintoHTML5.ep.io: Live Example... And checking if the placeholder tag is supported
DiveintoHTML5.ep.io: Placeholder text
1) Instead of checking for changes on the client side you can check for the changes on the client side.
In the Page_Init function you will have values stored in the viewstate & the values in the text fields or whichever controls you are using.
You can compare the values and if they are not equal then set the Text to blank.
2) May I ask, what functionality are you trying to achieve ?
U can achieve it by using this in your submit function
function clearDefaults()
{
if(document.getElementById('cs-Price-2').value=="Min. Price")
{
document.getElementById('cs-Price-2').value='';
}
}

Categories