I have a generic JavaScript function which takes one parameter
function foo(val) { ...}
and I want to call the function when submit a form
<form>
<input type="text" id="formValueId"/>
<input type="button" onclick="foo(this.formValueId)"/>
</form>
but the expression foo(this.formValueId) does not work (not surprised, it was a desperate attempt), So the question is, how can I pass a form value to the javascript function.
As I mentioned the javascript is generic and I don't want to manipulate the form inside it!
I could create a helper function in the middle to get the form values with jQuery (for example) and then call the function but I was wondering if I can do it without the helper function.
It might be cleaner to take out your inline click handler and do it like this:
$(document).ready(function() {
$('#button-id').click(function() {
foo($('#formValueId').val());
});
});
Give your inputs names it will make it easier
<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" onclick="foo(this.form.valueId.value)"/>
</form>
UPDATE:
If you give your button an id things can be even easier:
<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" id="theButton"/>
</form>
Javascript:
var button = document.getElementById("theButton"),
value = button.form.valueId.value;
button.onclick = function() {
foo(value);
}
Use onclick="foo(document.getElementById('formValueId').value)"
There are several ways to approach this. Personally, I would avoid in-line scripting. Since you've tagged jQuery, let's use that.
HTML:
<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" id="myButton" />
</form>
JavaScript:
$(document).ready(function() {
$('#myButton').click(function() {
foo($('#formValueId').val());
});
});
Well ya you can do that in this way.
<input type="text" name="address" id="address">
<div id="map_canvas" style="width: 500px; height: 300px"></div>
<input type="button" onclick="showAddress(address.value)" value="ShowMap"/>
Java Script
function showAddress(address){
alert("This is address :"+address)
}
That is one example for the same. and that will run.
More stable approach:
<form onsubmit="foo($("#formValueId").val());return false;">
<input type="text" id="formValueId"/>
<input type="submit" value="Text on the button"/>
</form>
The return false; is to prevent actual form submit (assuming you want that).
Related
I need each instance of input and submit to operate independently. What is the best way to handle multiple instances where each submit is connected to it's own set of inputs?
Since they are unrelated, would data-attributes be the best solution?
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item1">
<div><input type="text" name="name" autocomplete="off" required/></div>
<input type="submit" value="Submit 1" />
</div>
<div class="item2">
<div><input type="text" name="name" autocomplete="off" required/></div>
<div><input type="text" name="name" autocomplete="off" required/></div>
<input type="submit" value="Submit 2" />
</div>
I think your intuition about using data attributes works great here.
var allButtons = document.querySelectorAll("input[type=submit]");
allButtons.forEach(button => {
button.addEventListener("click", () => {
var inputSet = button.getAttribute("data-input-set");
var inputs = document.querySelectorAll("input[type='text'][data-input-set='" + inputSet + "']");
});
});
In the following code, when an input button is pressed, it will fetch all the inputs with the corresponding "input-set" tag.
Preferred way
I think best solution would be use form -tag as it is created for just this use case HTML Forms.
<form id="form-1">
<input type="text"/>
<input type="submit>
</form>
<form id="form-2">
<input type="text"/>
<input type="submit>
</form>
You can also bind custom Form on submit event handlers and collect form data this way.
$('#form-1').on('submit', function(event){
event.preventDefault(); // Prevent sending form as defaulted by browser
/* Do something with form */
});
Possible but more bolt on method
Alternative methods to this would be to create your own function's for collecting all relevant data from inputs and merge some resonable data object.
I would most likely do this with giving desired class -attribute all inputs I would like to collect at once eg. <input type="text" class="submit-1" /> and so on. Get all elements with given class, loop through all them and save values into object.
This requires much more work tho and form -tag gives you some nice validation out of the box which you this way have to do yourself.
Issue 1:
I'm trying to create a simple javascript function to check if all the characters entered into the field are numeric. The function is running, but not as I had hoped. I've located the isNaN function in javascript and it does not appear to be working. It enters the if statement every time, no matter if I type "asdf" or "1234" into the box.
Issue 2:
I want the form to stop submission obviously if the check for digits fails. However, I want it to continue to the submission page otherwise. I've been reading on ways to do this with pure JavaScript, and have the returns implemented as instructed. Is this a viable way to perform this? Alternatives?
Any help would be great on issue 1 or 2.
Here's my entire code:
<title>Bank System</title>
<script type="text/javascript">
function checkNumeric()
{
var pin = document.getElementById('pin');
if(isNaN(pin))
{
document.getElementById('message').innerHTML="Not A Valid Number";
return false;
}
else
{
return true;
}
}
</script>
<body style="background-color: gray;">
<h1>Welcome To Clayton's Credit Union</h1>
</br></br>
<form action="process.php" method="POST">
<label>Username: <input type="text" name="username"/></label>
</br>
<label>Pin Number<input type="text" maxlength="4" name="pin" id="pin"/></label>
</br></br>
<input type="submit" value="Submit" name="submit" onClick=" return checkNumeric()"/>
<p id="message"></p>
</br>
</form>
*Please note, I know this is not secure in anyway. I'm making this example specifically to show how vulnerable it is.
You are passing an element to isNaN rather than it's value. Try this:
var pin = document.getElementById('pin').value;
BTW
You should run this validation on the form submit rather than the button click:
<form action="process.php" method="POST" onsubmit="return checkNumeric()">
<input type="submit" value="Submit" name="submit" />
instead of:
<form action="process.php" method="POST">
<input type="submit" value="Submit" name="submit" onclick="return checkNumeric()" />
how can i get a specific element of a text input into a variable via javascript, in other words take the example below
<form id="123">
<input type="text" id="supply_qty" />
<input type="submit" name="submit" id="123" />
</form>
How do i get the element within the text input into a variable when the submit button is clicked, the problem i have is that i have multiple instances of the code above, with lots of text inputs, so i only want to get the element specific to the submit button clicked. Hopefully you will get what i mean. The reason i need this done via JavaScript and not php etc... is that i later want to use ajax with it, but for the moment i just need the variable.
Thanks
The most easiest way is to give and id to the element and user getElementById() method to grab the element on variable. Just like what you are doing right now
Simple Example:
var button = document.getElementyById("123");
button.onclick = function() {
var text = document.getElementById('supply_qty'); //now you got your element in varaiblle
};
Using jQuery make a slight change to your markup. I am just going to add some classes.
<form>
<input type="text" class="textbox" />
<input type="submit" class="submit" name="submit" />
</form>
then
$(".submit").click(function() {
var txtbox = $(this).parent("form").children(".textbox")[0];
});
Or, it might be better to bind to the submit handler of the form, on that case, give a common class to the form.
<form class="tinyforms">
<input type="text" class="textbox" />
<input type="submit" class="submit" name="submit" />
</form>
Then
$('.tinyforms').submit(function() {
var txtbox = $(this).children(".textbox")[0];
});
If you accept using jQuery you can do this:
DOM
<form class="form" action="false">
<input type="text" value="some input" name="textInput" />
<input type="text" value="some text" name="textInput2" />
<input type="submit" class="sumbit" value="Send" />
<div id="results"></div>
</form>
And JavaScript
$(".form").submit( function(){
var inputs = $(this).serializeArray();
$.each(inputs , function(i, input){
$("#results").append(input.value + "<br />");
});
return false;
} );
EDIT: Updated code and Fiddle: http://jsfiddle.net/65Xtp/4/
I am catching event of form submit and adding divs to the DOM, code http://jsfiddle.net/testtracker/7rkX4/7/
now i want to pass some arguments to the function like name of the commenter, time comment was added etc. I want it to be something like this.
html
<form onsubmit="addComment('john deo','post_id')">
<input ......>
<input ......>
</form>
javascript
function addComment(commenter_name,post_id){
perform operation....
}
The code you posted works fine. The reason it would not work in jsfiddle is because your functions are declared in a document.ready type of block by default (see the onLoad in the drop down on the left?)
The proper way to bind event handlers would be to bind them in javascript. This would avoid the scope problem.
If you need to get an inline event handler working, you can explicitly define your function as global:
window.addComment = function (commenter_name,post_id){
perform operation....
};
You can store the name of the commenter in html for example.
Try this (see demo: http://jsfiddle.net/7rkX4/8/).
HTML
<div class="post">
<ul class="comments"></ul>
<div class="comment_entry">
<form method="post" action="#">
<input type="hidden" name="name" value="Neha" />
<input type="text" name="comment" placeholder="Leave comment" />
<input type="submit" value="submit" />
</form>
</div>
</div>
<div class="post">
<ul class="comments"></ul>
<div class="comment_entry">
<form method="post" action="#">
<input type="hidden" name="name" value="Danil" />
<input type="text" name="comment" placeholder="Leave comment" />
<input type="submit" value="submit" />
</form>
</div>
</div>
JavaScript
$(document).ready(function () {
$('.comment_entry form').submit(function (e) {
e.preventDefault();
var name = $('input[name="name"]', this).val();
var comment = $('input[name="comment"]', this).val();
$(this).parent().prev().append('<li><a class="commenter_name" href="/">' + name + '</a><br />' + comment + '</li>');
});
});
If I understand correctly you want to add some variable-value pairs to the form on submit. Why not add some input fields to your form with type="hidden", then you can modify their values in your javascript code as you like.
I have two buttons, and I want to apply one action to another. For example.
<form>
<input type="submit" />
</form>
<input type="submit" />
I want to make the second button submit the form, despite being outside of the form.
You should make them of type button, and give your form an id.
Markup:
<form id="myForm">
<---STUFF---->
<input type='button' id='otherButton'>
</form>
<input type='button' id='someButton'>
jQuery:
$('#someButton').click(function() { $('#myForm').submit(); });
$(':input:last').click(function()
{
$('form').submit();
});
// enable form submit on the second <input>
$('input[type=submit]').click(function(){
$('form').submit();
});
// disable the inner <input>
$('form input[type=submit]').click(function(){
return false;
});
Something like this should do your trick.
If you want the second button to do everything the first can do (not just submit), you can try something like this:
html
<form>
<input id="insideButton" type="submit" />
</form>
<input id="outsideButton" type="submit" />
jsJQUERY
$("#outsideButton").click(function() {
$("#insideButton").trigger("click");
});
you can using jQuery $("#test").click() if you have jQuery instead of the document... stuff below or the way below will work without jQuery
<form name="testForm1">
<input type="submit" id="test" />
</form>
<!-- use this when not in a form: -->
<button onclick="button1_click();" id="button1"></button>
In your head tag
<script type="text/javascript">
function button1_click(){
document.forms.testForm1.submit();
}
</script>
Changed for the users that put performance under clean code