I have a form which I want to hide or show dependent on the users decision. I got following functions in an external javascript file:
function hide_element() {
$("form").hide();
};
function show_element() {
$("form").show();
};
and this is how I call those functions:
<button type="submit" onclick="show_element;">show</button>
<button type="submit" onclick="hide_element;">hide</button>
<form>
...
</form>
Unfortunately this does not work. Do you have any clues why this is the case?
Since we are using jQuery I would like to propose this approach:
HTML:
<button id='toggleMyForm'>hide</button>
<form id='myForm'>First name:
<br>
<input type=" text " name="firstname " />
<br>Last name:
<br>
<input type="text " name="lastname " />
<br>
<input type="submit" value="Submit"/>
</form>
jQuery:
var myForm = $('#myForm');
var toggleMyForm = $('#toggleMyForm');
toggleMyForm.on('click', function(){
myForm.toggle();
myForm.is(":visible") ? $(this).html('hide') : $(this).html('show');
});
Test here: http://jsfiddle.net/urahara/obm39uus/
NOTE: don't put yourself in the position where you have multiple submit buttons in a <form>, you can distinguish between them by using value attribute, but still in my opinion it's better to keep clean design with one submit per form.
don't repeat jQuery fetching calls. make a handle of a element:
var myForm = $('myForm'); then use it like this e.g: myForm.show()
replace show_element with show_element() & hide_element with hide_element() like below:
<button type="submit" onclick="show_element();">show</button>
<button type="submit" onclick="hide_element();">hide</button>
Now you try to call variables named show_element and hide_element. These doesn't exist.
Function has to be called with brackets. If you have no params, use ().
<button type="submit" onclick="show_element();">show</button>
<button type="submit" onclick="hide_element();">hide</button>
I recommend you to use <button type="button" class="hide">Hide</button>
And, in the js file :
$('button.hide').click(function() {
$('form').hide();
}
Same thing for the show button.
You've to replace "show_element;" with "show_element();".
<button type="submit" onclick="show_element();">show</button>
<button type="submit" onclick="hide_element();">hide</button>
But why?
The () Operator Invokes the Function.
Using the example above, show_element refers to the function object, and show_element() refers to the function result.
Example:
Accessing a function without () will return the function definition:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;
http://www.w3schools.com/js/js_functions.asp
With "show_element" you are able to store the function itself (in a variable for example), but you don't execute it.
is this pseudo-code?
If not I would rewrite it like:
$form = $('#form_id');
function hide_element() {
$form.hide();
$form.submit();
}
function show_element() {
$form.show();
$form.submit();
}
And then:
<button onclick="show_element();">show</button>
<button onclick="hide_element();">hide</button>
<form>
...
</form>
I removed the type submit because it is not good to have more than one submit. Actually both are outside the form. In case you want to submit it I would put it like this:
<button onclick="show_element();">show</button>
<button onclick="hide_element();">hide</button>
<form>
...
</form>
Related
I have two submit buttons in a cshtml file.
<button type="submit" name="SubmitButton" value="accept" id="buttonAccept">Accept</button>
<button type="submit" name="SubmitButton" value="refuse" id="buttonRefuse"Refuse</button>
I am trying to disable these two buttons when either one of them is clicked.
Is there a way to do so?
You can use the similar code for both buttons. onClick on one button disable the other button and so.
<button type="submit" name="SubmitButton" value="accept" id="buttonAccept" onclick="return foo();">Accept</button>
function foo() {
document.getElementById("buttonAccept").disabled = true;
document.getElementById("buttonRefuse").disabled = true;
return true;
}
you can use javascript (especially jQuery) to reach your purpose.
but, actually when you submit your form, it means your form is sent to your server and it returns new result of your view, so the next steps will happen in the backend, your backend will be responsible to render the result in the way you want.
$('#buttonAccept').on("click",function() {
$('#buttonRefuse').attr("disabled", "disabled");
});
$('#buttonRefuse').on("click",function() {
$('#buttonAccept').attr("disabled", "disabled");
});
This should do it:
document.getElementsByName("SubmitButton")[0].disabled = true;
document.getElementsByName("SubmitButton")[1].disabled = true;
I wouldn't use the index directly though.
You can Do like this.
For Disabling the Button in Front-end using Pure JavaScript
<button onclick="document.getElementById('ButtonTwo').disabled = true;" type="submit" name="ButtonOne" id="ButtonOne">First</button>
<button onclick="document.getElementById('ButtonOne').disabled = true;" type="submit" name="ButtonTwo" id="ButtonTwo">Second</button>
firstly add jquery if your page don't have one
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
then add on click event like this
<button type="submit" name="SubmitButton" value="accept" id="buttonAccept" onclick="EnableDisable()">Accept</button>
<button type="submit" name="SubmitButton" value="refuse" id="buttonRefuse" onclick="EnableDisable()">Refuse</button>
then you can disable both submit button on any of there click event like this
function EnableDisable() {
$(':input[type="submit"]').prop('disabled', true);
}
I know this question has been asked already.
However, when I follow the answer given to that question it doesn't work.
This is my JS function and the relevant HTML
function myFunction() {
document.getElementById("submit").innerHTML = "LOADING...";
}
<input class="textbox" type="number" id="number">
<button onclick="myFunction(document.getElementById("number").value)" class="Button" >Submit</button>
<p id="submit"></p>
<script type ="text/javascript" src="../src/index.js"></script>
Strangely none of the answers recommended separating the HTML and JavaScript, so that's what I'll do. It's considered a best practice to not inline JS in your HTML.
const button = document.querySelector('button');
button.addEventListener('click', myFunction, false);
function myFunction() {
console.log(document.getElementById('number').value);
document.getElementById("submit").innerHTML = "LOADING...";
}
<input class="textbox" type="number" id="number">
<button class="Button">Submit</button>
<p id="submit"></p>
Try this...
Get the value insert the function.... It will display your desire output....
function myFunction() {
var number = document.getElementById("number").value;
document.getElementById("submit").innerHTML = "LOADING...";
}
<input class="textbox" type="number" id="number">
<button onclick="myFunction()" class="Button" >Submit</button>
<p id="submit"></p>
<script type ="text/javascript" src="../src/index.js"></script>
Like the earlier answer, you need to use single quote around 'number'. Another thing, you need to add parameter val in the myFunction(val) in the index.js.
function myFunction(val) {
document.getElementById("submit").innerHTML = "LOADING...";
console.log(val);
}
I thought, You used inside double quote("), using double quote("). So Please change double quote inside single quote(') or single quote inside double quote("). More over button default type is submit...
Change following
<button onclick="myFunction(document.getElementById("number").value)" class="Button" >Submit</button>
Into
<button onclick="myFunction(document.getElementById('number').value)" class="Button" >Submit</button>
or
<button onclick='myFunction(document.getElementById("number").value)' class="Button" >Submit</button>
javascript
function myFunction() {
document.getElementById("submit").innerHTML = "LOADING...";
}
Into
function myFunction(num) {
var n = num;//Get the number into your javascript function
document.getElementById("submit").innerHTML = "LOADING...";
}
<input class="textbox" type="number" id="number">
<button onclick="myFunction(document.getElementById('number').value)" class="Button" type="button" >Submit</button>
<p id="submit"></p>
<script type="text/javascript">
function myFunction(num){
var n = num;
console.log(n);
document.getElementById("submit").innerHTML = "LOADING...";
}
</script>
Default type of the button element is submit (and it is ok; the data will be submitted to the server). If something should be done before submission then it could be processed like this.
function myFunction(element, evn) { //here you can rename parameters
//evn is click event, element is the button clicked
evn.preventDefault(); //don't submit form at this moment
document.getElementById("submit").innerHTML = "LOADING...";
//now it is safe to submit the form
//setTimeout is for demonstration purpose
setTimeout(function() {
element.form.submit();
}, 1000);
}
<!-- form tag supposed to be open -->
<form method="get" action=".">
<input class="textbox" type="number" id="number" name="numData">
<!--name attr is required to send data to the server -->
<!-- note the arguments sent to the function.
Don't change them -->
<button onclick="myFunction(this,event)" class="Button">Submit</button>
<!-- form tag may be closed here or later -->
</form>
<p id="submit"></p>
<script type="text/javascript" src="../src/index.js"></script>
In the example below I've attached a function main to an input field. the function contains instructions to send an alert with a variable message (whatever the user enters into the field).
<form>
<input type="text" onsubmit="main()" />
<input type="submit" />
</form>
<script>
function main (param) {
alert(param)
}
//main();
</script>
It doesn't work, but I believe that's because I've made some noob error that I'm failing to recognize. The result of a functioning version of this code would be the ability to submit "hello world" and produce an alert box stating 'hello world' (without quotes).
But, further than this, I'd like to be able to pass the likes of main("hello world"); or just alert('hello world'); to the input field to produce the same result.
The problem I think I'm running into is that the page is refreshed every time I submit. There are a few questions on here with similar problems where people have suggested the use of onsubmit="main(); return false;", but in fact this does not seem to work.
Looks like you want to eval() the value of the input.
Use with caution, has security impact...
Returning false from a handler stops the regular action so you have no redirect after submitting:
<form onsubmit="main(); return false;">
<input id="eval-input" type="text" />
<input type="submit" />
</form>
<script>
function main () {
eval(document.getElementById('eval-input').value);
}
</script>
Here's how you can detect a form submission:
<form onsubmit="foo()">
<input type="text">
<input type="submit">
</form>
<script>
function foo(){
alert("function called");
}
</script>
I however advise you do this (preference), if you desire to manage the form data through a function:
<form id="myform">
<input type="text">
<input type="submit">
</form>
<script>
document.getElementById("myform").onsubmit=function(event){
alert("function called");
//manage form submission here, such as AJAX and validation
event.preventDefault(); //prevents a normal/double submission
return false; //also prevents normal/double a double submission
};
</script>
EDIT:
use eval() to execute a string as JavaScript.
jQuery way:
You create event listener which will be triggered when user click 'submit'.
<form>
<input type="text" id="text"/>
<input type="submit" />
</form>
<script>
$( "form" ).submit(function( event ) {
event.preventDefault();
alert( $('#text').val() );
});
</script>
To prevent page reloading - you should use event.preventDefault();
Pure JavaScript:
<form>
<input type="text" id="text"/>
<input type="submit" id="submit" />
</form>
<script>
var button = document.getElementById("submit");
var text = document.getElementById("text");
button.addEventListener("click",function(e){
alert(text.value);
},false);
</script>
If I understand what you want to do, you can call the function like this, and writing params[0].value you can access the input value:
function main(params) {
//dosomething;
document.write(params[0].value);
}
<form onsubmit="main(this)">
<input type="text">
<input type="submit">
</form>
Try something like this
onchange="main()"
onmouseenter, onMouseOver, onmouseleave ...
<input type="text" onmouseenter="main()" />
I have an HTML form that I submit after changing the action with some javascript. Two different buttons can do the submit.
The interesting thing is that I was trying to debug it and inserted an alert after changing the action and before submitting the form. The form is submitted without the alert ever being displayed. To make sure it's actually performing the javascript, I added an alert before changing the action. That alert displays; the alert after changing the action does not.
<form name='FormSelect' method='post' action='Undefined'>
...
<button onclick="SubmitForm('class')">Submit</button>
...
<button onclick="SubmitForm('student')">Submit</button>
...
</form>
<script type="text/javascript">
function SubmitForm(target){
alert("Action 1: " + document.FormSelect.action);
if (target=="class") {
document.FormSelect.action = "ClassAction.php";
} else {
document.FormSelect.action = "StudentAction.php";
}
alert("Action 2: " + document.FormSelect.action);
// document.FormSelect.submit();
}
</script>
Is that the expected sequence of events?
Any button placed inside form element will cause submit action. To prevent this you can add type="button" to button elements, or make you submit callback return false;
<button type="button" onclick="SubmitForm('class')">Submit</button
see http://jsfiddle.net/yD2Uu/
As the others have already pointed out the form will be submitted anyway if you don't cancle the event. I want to suggest a JavaScript free solution to your problem.
<button formaction="ClassAction.php">Submit</button>
<button formaction="StudentAction.php">Submit</button>
It's not supported in IE < 10 though. But you can still use your function as a fallback then, just a bit more elegant ;)
function SubmitForm(button){
button.form.action = button.formaction;
}
A better solution is to give the buttons a name each and submit to Action.php and let the server get the value of the named button
$student = filter_var($_POST["student"], FILTER_SANITIZE_STRING); // php5 cleaning
when you have
<form method="post" action="Actions.php">
<input type="submit" name="student" value="John Doe" />
<input type="submit" name="student" value="Jane Doe" />
<input type="submit" name="student" value="Whatever Doe" />
</form>
Otherwise if you must
Try this
<form method='post' action='Undefined'>
...
<input type="button" value="Class" onclick="SubmitForm(this)" />
...
<input type="button" value="Student" onclick="SubmitForm(this)"/>
...
</form>
<script type="text/javascript">
var actions = {
"class":"ClassAction.php",
"student":"StudentAction.php"
}
function SubmitForm(button){
button.form.action = actions[button.value];
button.form.submit();
}
</script>
Thanks to Yauhen Vasileusky's example, I started removing code between my 1st & 2nd alerts and found that the problem seems to be the following IF statement:
if (document.FormSelect.FormName.value.substr(0,19)=="ObservationRequest_" || document.FormSelect.FormName.value=="StudentReg2013rx" || document.FormSelect.FormName.value=="Toddler Update Form v3rx")
{
document.FormSelect.action = "GenerateXDP.php";
}
When I remove it, both alerts are displayed. So the answer to my question is that changing the action does not submit the form; it was some other error in my code that made it appear as if that was the case.
I have a complicated case here, but below is an example just to make it simple.
I have two buttons, each with their own onClick function. I want to call the onClick function of button A when I click on button B.
<input id="buttonA" type="button" value="BUTTON A" onMouseUp="sayHiA()"></input>
<input id="buttonB" type="button" value="BUTTON B" onClick="sayHiB()"></input>
Note that the event can be onClick() or onMouseUp()
p.s. I have to do it using only javascript. (NO jQuery). Thanks
<input type="button" onclick="fnc()"/>
<input type="button" id="message" onclick="alert('ok')" />
<script type="text/javascript">
function fnc()
{
document.getElementById("message").click();
}
</script>
are you looking for this?
<html>
<head>//I guess something like setTimeout(function,timeInMilliseconds)
<script language = "javascript">
function sayHiA(){
var v = document.getElementById('buttonB').getAttribute("onClick");
setTimeout(v,0);
}
function sayHiB(){
document.getElementById('para').innerHTML = 'wrote';
}
</script>
</head>
<body>
<input id="buttonA" type="button" value="BUTTON A" onMouseUp="sayHiA()"></input>
<input id="buttonB" type="button" value="BUTTON B" onClick="sayHiB()"></input>
<p id = "para">
Write Here
</p>
</body>
</html>
function sayHiB() {
sayHiA();
}
Did you tried this with an external js ? This is quite the most basic thing you can do in javascript.
I made you a jsfiddle : http://jsfiddle.net/pjDVP/4/
The html :
<input id='bta' type='button' value='button a'></input>
<input id='btb' type='button' value='button b'></input>
The js (with jquery laoded) :
$(function(){
$('#bta').click(function(){aORbClick();});
$('#btb').click(function(){aORbClick();});
})
function aORbClick(){alert('I clicked a or b');}
just call function sayHiA from sayHiB or call it after.
Call from sayHiB
function sayHiB()
{
sayHiA();
}
or after
<input id="buttonB" type="button" value="BUTTON B" onClick="sayHiB(); sayHiA();"></input>
or easier way is to use jQuery, so you can do this
function sayHiB(){
if($('#id-of-a').attr('onclick'))
$('#id-of-a').click();
else if ($('#id-of-a').attr('onmouseup'))
$('#id-of-a').mouseUp();
}
function sayHiB(){
$('#buttonA').click();
}
Raw JS:
function sayHiB(){
var buttonA = document.getElementById('buttonA');
buttonA.onclick.apply(buttonA); // in onclick function you can get buttonA as 'this'
}
I'd probably make a generic function that switches on the button's name/id to figure out what to do - this would also make your code work independent of the event attribute used to call the function.
HTML:
<input id="buttonA" type="button" value="BUTTON A" onMouseUp="myFunc(this)"></input>
<input id="buttonB" type="button" value="BUTTON B" onClick="myFunc(this)"></input>
JavaScript:
function myFunc(elem){
switch(elem.id){
case 'buttonA':
sayHiA();
break;
case 'buttonB':
sayHiB();
sayHiA();
break;
}
}
This would also help with any DOM manipulation you might need as the button which was clicked is passed to the generic function myFunc, allowing you to quickly access other attributes or nearby elements.