Get textbox value through button in popup - javascript

I am a newbie to chrome-extension/java script development and I am stuck at the following exercise.
I created a popup with a button and a textbox. I wanted to pass the textbox value to an alert when the submit button is pressed. I have the following code so far:
popup.html
<div id="popup"></div>
<form name="q">
<input name="query" id="userQuery" type="text" />
<button id="button1">Submit</button>
<!-- <input type="button" name="button" value="query" /> -->
</form>
popup.js
document.addEventListener('DOMContentLoaded', function () {
console.log(document.getElementById('userQuery'));
document.getElementById('button1').addEventListener('click', myAlert(document.getElementById('userQuery')));
});
function myAlert(query){
alert(query.value)
}
However, I get "null" as query.value so the alert comes empty.
I also noticed that when the extension is clicked for the popup, I get an alert as well, which I don't understand why, I used both 'click' and 'onclick' but I get the same issue.
Any hint or help will be much appreciated!

One way to do it:
document.getElementById('button1').addEventListener('click', function() { myAlert(document.getElementById('userQuery')); });
In your code, the expression myAlert(document.getElementById('userQuery')) is evaluated when addEventListener is called. That's why you see a blank alert when the page loads. Instead you need to pass a function, that will be executed when the click event happens.

Try this $("#userQuery").val() OR document.getElementById("userQuery").value
instead of document.getElementById('userQuery')

Related

How to create an HTML <input> submit button that saves all data to JS variables?

I know I can create several types of options, questions, checkboxes, and buttons using in HTML. How can I save the response a user enters and assign it to a variable? Here's the code I'm using right now:
HTML:
<input type="text" value="Hotel Name" id="questionOne"><h1 display="block">WHAT IS THE NAME OF THE HOTEL</h1><br>
<input type="button" value="HELLO" onclick="testFunction()">
JS:
function testFunction() {
prompt(document.getElementById("questionOne").value;);
}
Shouldn't it activate the function when the HELLO button is clicked, and then it identifies the response through the ID "questionOne" and creates a prompt with the variablev value? I don't understand why it's not working.
I'm new to JS and HTML so please don't go crazy if it's a simple answer. Thank you.
I think your problem is to do with where things are defined. Rather than using onclick, add an event listener in your js. e.g.
document.getElementById ("bar").addEventListener ("click", foo);
function foo() {
prompt(document.getElementById("questionOne").value);
}
and just change the button to have an id and get rid of the onclick:
<input type="button" id="bar" value="HELLO">
Well you can just add event Listener to your input.
Like
document.getElementById('questionOne').addEventListener('input',function(){
var somevariable = prompt(this.value,'');
});
That will save the answer of prompt to 'somevariable'.

How do I permanently store input from an HTML text field into a jQuery variable?

jQuery
$(document).ready(function(){
var guess;
$('#submit').on("click", function() {
guess = $('#guess-value').val();
$("#value").text(guess);
alert(guess);
});
alert(guess);
});
HTML
<div id='game'>
<form id='user-input'>
<input type='text' id='guess-value' placeholder='1-100'></input>
<button id='submit'>Submit</button>
</form>
<h4 id='guess-count'>Attempts left: <span id="attempts">6</span></h4>
</div>
<h4 id='checker'>The value entered is <span id="value">?</span></h4>
I've provided snippets of my HTML and jQuery code above. I am trying to store a number that has been entered into a text field, into a jQuery variable called guess after pressing a submit button.
The following happens occurs:
When I enter a number into the field and press submit, I get an alert showing the value I entered. After closing the event I get another alert that is supposed to show the value of 'guess' and the value is undefined.
This happens even though I declared the variable guess outside of the click event. Why is this and how do I permanently store the value?
You are using a <form> element to ask for user input. The problem with a form, is that when it submits, it wants to navigate away from (or refresh) the page. When the page refreshes, all js is lost.
Simple fix: don't use a form (you can use a DIV instead).
Alternatively, you can tell the form to NOT do its default action of submitting by using event.preventDefault():
jsFiddle Demo
HTML:
<div id='game'>
<form id='user-input'>
<input type='text' id='guess-value' placeholder='1-100'></input>
<button id='submit'>Submit</button>
</form>
<h4 id='guess-count'>Attempts left: <span id="attempts">6</span></h4>
</div>
<h4 id='checker'>The value entered is <span id="value">?</span></h4>
<input type="button" id="myButt" value="Show Value" />
jQuery:
var guess;
$('#submit').on("click", function (evnt) {
guess = $('#guess-value').val();
$("#value").text(guess);
alert(guess);
evnt.preventDefault();
});
$('#myButt').click(function(){
alert( guess );
});
Further Notes:
Note that the 2nd alert(guess) in your posted code will occur immediately upon document.ready. I mean, immediately -- as soon as the DOM is ready. Before anything has been put into guess. That is why it returns undefined.
That is probably not what you want. Code example above adds a button to allow you to view that variable's contents when desired.
The function : $("#value").text(guess) is not corret in this case, replace it with :
$("#value").empty().append(guess);
you should wait to be .ready() in order to submit();
give me feedback please. enjoy :)
The 'guess' variable is out of the click event handler but it's in the ready event handler; So the second alert box will be shown exactly once when the page is loaded. It will then be undefined. The click events will occur later.

Javascript function prints .innerHTML but HTML only appears for a moment before vanishing

I've got a button that calls a javascript function named "submit()". In that function I simply write document.getElementById('try').innerHTML="it worked"; to test out whether or not my button is passing data to the function or not.
The problem is "it worked" gets printed for about a half second before disappearing.
I made an entire form that printed processed data to the webpage perfectly using the same html page. The only difference is that I changed the structure of my form and moved my functions to a .js file.
Although now, even if I comment out the submit() function in the .js file and paste the function within the core html file the same thing happens. I can paste is above or below the form and the same thing results.
Here is my HTML:
<div class="formsection">
<button type="Submit" onclick="Submit()">Submit</button>
</div>
</form>
</div>
<div id="output">
<p> Try this: <span id="try"></span></p>
</div>
Here is my javascript function:
<script type="text/javascript">
function Submit(){
document.getElementById("try").innerHTML="It worked";
}
</script>
you are using submit button to test your code, it executes the JS code and submitted the form.
If you don't want the form to be submit use return false in submit()
<script type="text/javascript">
function Submit(){
document.getElementById("try").innerHTML="It worked";
return false;
}
</script>
and in html again use return
<button type="Submit" onclick="return Submit()">Submit</button>
In javascript when any event handler returns false that halts the event execution.
The issue you're experiencing is due to your markup, mainly this piece:
<button type="Submit" onclick="Submit()">Submit</button>
You've specified that the button should perform a form submission when clicked, hence the javascript fires, changes the text and the page is reloaded (post back occured).
To get around that, you implement one of the following changes:
Change your markup to just be a button that fires javascript:
<input type="button" onclick="Submit()">Submit</input>
Add a statement in your javascript that cancels the default action for your submit button:
event.preventDefault(); MDN Link
Your form is submitted, that's why you see "It worked" only for a second (if at all).
Your function isn't prevents form submission.
You can use onsubmit attribute of form to specify function which will be called before form is submitted and can decide whenever it allowed or not by returning Boolean value
Your form actually gets submitted:)
Use this:
<button type="Submit" onclick="Submit(); return false;">Submit</button>
I don't see the FORM tag but if you do something like:
<form action="javascript:" onsubmit="Submit()">
Your function Submit will be called, and nothing more.
The nice thing about using a input type="submit" is your user can submit a form by hitting Enter and don't have to manage it yourself.

Javascript onsubmit causing page to refresh

Really simple form
<form id="addDonor" name="addDonor" onsubmit="addDonor(); return false;" action="" method="post" enctype="multipart/form-data">
<div class="sectionHeader">Add New Donor</div>
<div class="formRow"><label>Name</label> <input class="inputText fullTextBar" type="text" name="userName">
<div class="formRow"><button style="margin-left:350px; width: 80px" type="button" class="publish">Add Donor</button></div>
</form>
And the addDonor function
<script type="text/javascript">
function addDonor(){
alert("test");
return false;
}
</script>
Eventually that function will include some jquery ajax to submit the info. But, baby, steps. Right now I can't even get the alert to show up. Also, when I hit "Enter" on my keyboard, the whole page refreshes, when I press "Add Donor" nothing happens.
I'm sure it has to be a simple problem. I think it's one of those things that I just need someone else's eyes to point out.
Try assigning the onsubmit event in javascript:
document.getElementById("addDonor").onsubmit = function () {
alert("test");
return false;
}
The problem is that your function is named addDonor and your element is addDonor. Every element with an id has an object created under document to identify it. Try alert(addDonor) in the inline onsubmit to see that it alerts an HTML element, not a function. Inline functions execute in a scope chain inside document, so addDonor points to document.addDonor before it reaches window.addDonor (your function).
you should change your <button> to an <input type="submit"> (as #fireshadow52 suggested) that should fix your problem. you should try the Wc3 Schools online javascript tester to try out simple javascripts before you put it in a page, or any other one that you prefer. google has something along these lines. also, you can normally try the javascript console on your respective browser.
Your button is explicitly set to type="button", which won't make it submit the form. Change it to <button type="submit">, or to <input type="submit"> if you prefer (I like the styling options of <button> myself).

HTML Button behaving badly

I added a button that is supposed to open a calendar 'date-picker'. The button is in a form that is rendered inside an EXTJS TabPanel. When the button is clicked, it causes the EXTJS tab panel to reload. Even if I remove everything but the following (making it a dumb button) the page still reloads.
<button id="calendar-trigger">...</button>
Edited: derived from: http://www.dynarch.com/projects/calendar/doc/
<input type="text" id="id_activity_date" name="activity_date">
<input type="button" value="..." id="calendar-trigger">
<script type="text/javascript">
new Calendar({
trigger : "calendar-trigger",
inputField : "id_activity_date",
onSelect : function() { this.hide() }
});
</script>
I don't want the reload to happen and I can't figure out why the reload is happening. or how to stop it. Something is getting triggered beyond just the button click. I suspect that EXTJS is causing it, but I can't figure out why.
I would like to start by killing all code that is triggered by this button. I want to make this a dumb button that doesn't do anything when clicked.
What is likely going on here? and How can I fix it?
Try this instead:
<input type="button" id="calendar-trigger" value="Button Label">
I've had trouble with <button> tags trying to submit forms and what not when they should not. Using an <input> tag with a type of "button" seemed to help me - maybe it will work for you as well.
If you have a <button> tag on a form which does not have a submit button (<input type="submit">), the <button> becomes the input button by default, apparently.
In HTML, <button> has a type attribute. The default value for type is submit, meaning that unless you specify type="button" (or something else), the button will trigger the submission of the form it is associated with. That is probably what is causing your page to reload (because the form is being submitted).
Alternatively, you could use <input type="button" id="calendar-trigger" />.
I would recommend using <input> as opposed to <button>
<input type="button" value="Click Me" id="calendar-trigger" />
Typically the <input type="submit" /> will make a submit button when in a form, I suspect that is what the <button> tag is doing.

Categories