MVC Javascript Button Value Incorrect - javascript

I am using MVC - in one of my views I have a button that I want to toggle the value on click. Here's the button code in the view:
<div class="col-md-10">
<input type="button" value="Yes" class="btn btn-default" id="CanOrder" />
</div>
And this is my javascript for its click event:
<script>
$('#CanOrder').click(function () {
if ($(this).val('Yes')) {
alert("button says Yes");
$(this).val('No');
}
else {
alert("button says No");
$(this).val('Yes');
}
});
</script>
At the very beginning, this works...the button shows "Yes", and when I click on it I get the alert "button says Yes" and then it changes to "No".
But after that, what happens is whenever I click on it, it immediately changes the text on the button to "Yes", then I get the alert saying "button says Yes", and it changes back to "No".
If I try running the page without the alerts, I don't even see it ever change back to "Yes" - it acts like clicking it the first time works and then it only ever says "No" whenever I click on it after that.
What am I doing wrong?
Thank you!

In order to check the value of CanOrder you need to correct your if statement:
<script>
$('#CanOrder').click(function () {
if ($(this).val() === "Yes") {
alert("button says Yes");
$(this).val('No');
}
else {
alert("button says No");
$(this).val('Yes');
}
});
</script>
You can learn more about the val method here.

Related

How to have multiple submit buttons for a quiz on one page

I'm creating a language quiz and it requires multiple submit buttons on one page through which one can check their answers. Having one submit button works fine. But so far, having multiple submit buttons creates issues where one submit button, when pressed, generates two (if there are 2 questions) of the same answers under both submit buttons. So after one click you will see 4 of the same answers. And only one submit button will be disabled. See scripts below for more info.
Below you'll find the html form for 1 of the quiz questions.
<form id="formId">
<h5>1. I am strong</h5>
<p>Translate the above sentence.</p>
<input type="text" id="q1" /><br><br>
<input type="submit" class="btn btn-outline-primary" id="submitId" value="Check answer" />
</form>
Below you'll find the javascript that gives the answer when submit button is clicked.
<script>
var answers = {
"q1": ["Ik ben sterk"]
};
function markAnswers(){
$("input[type='text']").each(function(){
console.log($.inArray(this.value, answers[this.id]));
if($.inArray(this.value, answers[this.id]) === -1){
$(this).parent().append("<br>The correct answer: Ik ben sterk");
} else {
$(this).parent().append("<br><font style='color:green;'>Correct!</font>");
}
})
}
$("form").on("submit", function(e){
e.preventDefault();
markAnswers();
});
</script>
The script below is to make sure user cannot submit answer again.
<script>
var form = document.getElementById('formId');
var submitButton = document.getElementById('submitId');
form.addEventListener('submit', function() {
// Disable the submit button
submitButton.setAttribute('disabled', 'disabled');
// Change the "Submit" text
submitButton.value = 'Check answer';
}, false);
</script>
Above scripts are just for one question. If I add another question and I copy paste scripts and change the ID's to q2, formId2 and submitId2 it will not work as described earlier. What do I need to change to the scripts in order for this to work? Any suggestion is welcome. Thanks.
Your markAnswers function is looping through all inputs, that's why you're getting the answers for all of them when you click any of the buttons.
You can fix this by changing the id of the forms to be like formId1, formId2 etc., then giving that id to the markAnswers function.
Example:
function markAnswers(id) {
$(`#q${id}`).each(function () {\
if ($.inArray(this.value, answers[this.id]) === -1) {
$(this).parent().append(`<br>The correct answer: ${answers[this.id]}`);
} else {
$(this).parent().append("<br><font style='color:green;'>Correct!</font>");
}
});
}
$("form").on("submit", function (e) {
e.preventDefault();
const id = e.target.id.replace("formId", "")
markAnswers(id);
});
Additionally, you can disable the button in the same submit event as well:
$("form").on("submit", function (e) {
...
$(`#submitId${id}`).each(function () {
this.setAttribute('disabled', true);
this.value = "Check answers"
})
});
Here's a working example: Codesandbox

enable or disable a button on another page

How would I be able to click a button on one page, that will enable another button on another page?
my javascript
function enableButton2() {
document.getElementById("button2").disabled = false;
document.getElementById("divbutton").hidden = false;
}
HTML
<input type="button" id="button1" value="button 1" onclick="enableButton2()"/>
<div id="divbutton" hidden>
<input onclick="window.location.href='menu.html'" type="button" id="button2" value="button 2" disabled />
</div>
this code works but will only work if both these buttons are on the same page, what I'm trying to do is separate them into their own pages but still work as intended, that is clicking the first button will make the second button appear.
Thanks in advance!
localStorage would be an efficient approach if you also want to save the user's button choice. localStorage allows you to store a value in the same origin, which means you just have to check whether the value was changed and differentiate which button should be enabled.
For example,
function enableButton2() {
localStorage.enabledButton = '2'
}
Then to check which button to enable, which would be used in the second page
setInterval(() => {
if (localStorage.enabledButton == "1") {
//Enable button 1
}
if (localStorage.enabledButton == "2") {
//Enable button 2
}
})
You can use Broadcast Channel API to communicate between different tabs.
For example, declare the following on both pages:
const bc = new BroadcastChannel('button_disable');
bc.onmessage = function(event){
if(event.data == "hide"){
//hide the buttons
}else if(event.data == "show){
//show the buttons
}
}
Then, if you want to hide/show the button, simply dispatch a message:
bc.postMessage('hide');

How to detect button value change in JQuery?

I've a sign up form which has submit button with value "GET INSTANT ACCESS!" :
<input type="submit" class="wf-button" name="submit" value="GET INSTANT ACCESS!">
After submit, the value gets change to 'Thank You!':
<input type="button" class="wf-button" value="Thank You!">
I need to detect the button value. If it becomes "Thanks You!" then I have to show a popup. And this value gets change by some Ajax (GetResponse form). There is no page refresh.
I've tried below code but it is only working in FireFox & not working in Chrome.
<script>
$(function() {
$(".modalbox").fancybox();
});
$(function() {
$('.wf-button').bind("DOMSubtreeModified",function(){
//if btn valu is 'Thank You! trigger popup'
$(".modalbox").trigger('click');
});
});
</script>
Live URL: http://www.idynbiz.com/web/html/gold_ira_vf/? (just to show how the button changes its value)
Can some one help how can I detect the button value and show my popup? The button change its value in real time (Ajax). There is not page refresh.
Is there any JQuery approach with bind() Or on() function to detect the value?
$(function() {
$('.btn1').on('change', function() {
alert('Do stuff...');
});
$('.lnk1').on('click', function() {
$('.btn1').val('Thank you!');
$('.btn1').trigger('change');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="submit" class="btn1" value="SUBSCRIBE" />
Change button value
OK ,
when button is clicked and form is submitted for saving. just write these code
$(document).ready(function ()
{
$('.wf-button').click(function ()
{
var valueofbutton = $(this).attr('value');
if(valueofbutton == 'Thank You!')
{
window.open(); //// whatever you want to open in popup
}
});
});
i m sure that this will work
You can use the following function in javascript which gets called after any > kind of postback, i.e. synchronous or asynchronous.
function pageLoad()
{
if($(".wf-button").val()=="Thank You!")
{
// show your popup
}
}
Hope it works....

Trigger functions from checkbox on click by clicking on a button

I have a couple of checkboxes and a button. When I click on checkbox - function is triggered. This is the desired behavior but I want to trigger it by clicking on the button. I want to have the possibility to first select checkboxes (I tried with return false and event.preventDefault but these completely switch the selection off) and then by clicking the button - trigger functions from checkboxes. Here is a link to jsfiddle:
http://jsfiddle.net/j93k2xns/6/
So for instance: I can select 3 checkboxes (nothing should happen) and after I click the button - three alerts should appear.
The code:
HTML:
<input type="checkbox" name='check[]' id="first">first</input>
<input type="checkbox" name='check[]'>second</input>
<input type="checkbox" name='check[]'>third</input>
<input type="checkbox" name='check[]'>fourth</input>
<input type="button" value="validate" id="val-button">
JS:
var check_state;
$(document).on('click','input[name="check[]"]', function(e){
if(check_state === true) {
alert('a');
} else {
return false;
}
});
$(document).on('click','#val-button', function(){
check_state = true;
});
There are a few interpretations to his question. If I'm reading it correctly, he wants to bind an arbitrary function to the checkboxes. Clicking the button should fire this event. This is how you can achieve that using custom events in jQuery:
$(function () {
$("input[name='check[]']").bind("myCustomButtonClick", function() {
if(this.checked) {
alert('a');
}
});
})
$(document).on('click','#val-button', function(){
$("input[name='check[]']").trigger("myCustomButtonClick");
});
And the associated jsfiddle: http://jsfiddle.net/3yf7ymos/
$(document).on('click','#val-button', function(){
$( 'input[name="check[]"]' ).each(function( index ) {
if($(this).is(':checked')) {
alert("a");
return true;
}
});
});
If you want to do something when the user checks a checkbox, add an event listener:
$('input[type="checkbox"]').click(function() {
if ($(this).is(':checked')) {
// do something
}
});
If the idea is run a couple of functions after the inputs are checked by clicking on a button:
function myFunction() {
if ($('input[id="something"]:checked').length == 0) {
// do something
} else if ($('input[id="something_2"]:checked').length == 0) {
// do something
}
//and so on..
}
$('#val-button').click(function() {
myFunction();
});
I have a similar inquiry. I have a number of check boxes. Each checkbox is linked to a different URL that opens a PDF form. I want my team to be able to select which forms they need by ticking the checkbox. Once they have done that, I would like a button to trigger the opening of each form based on which check box is checked. I have it so the checkbox upon being checked opens the form right away but it is very distracting. Its preferable they all get opened at once by a "button". Help. I am quite new to JavaScript so may need additional clarity.

Submit form with two submit buttons, each performing different actions issue

I have a JSP page, which has standard form on it. I have two buttons, each perform a different action when pressed, and the form is submitted - action 1 and action 2.
I originally had this set up for one button, so it was all done through the following and worked fine:
$('#form').submit( function() { .... }
But now I have two buttons, I want it to do the same, but how to find which button I pressed.
I could do this through the .click function, but I dont want to break my existing form.submit functionality.
Below is my code for this - which doesn't work:
$('#form').submit( function() {
// Set the field array variables with data
$('button[name="action1"], [name="action2"]').each(function(index) {
alert('index : ' + index );
alert('value : ' + this.value);
});
$('button[name="action1"]').click(function(e) {
alert('ac1 clicked');
});
$('button[name="action2"]').click(function(e) {
alert('ac2 clicked');
});
my html buttons are:
<button id="submitButton" name="action1" value="action1" type="submit">action 1</button>
<button id="submitButton" name="action2" value="action2" type="submit">action 2</button>
Is there a way I can do this inside my form.submit, or a way to do the .click, which then submits the form. I am a little lost for a solution on this?
Please help :)
You can read the related target of the event object.
$('#form').on('submit', function(evt) {
if (evt.relatedTarget && $(relEl).is('input[type=submit]')) {
/* related element is a button - do something */
}
evt.preventDefault(); //cancel form submit, as required
});
In the button's click handler, set a hidden field before submitting the form. Then read the value of that hidden field in the request handler to find out which action was requested.
Bind a event handler to your buttons
$('button').on('click', function(e) {
var buttonId = $(this).attr('name');
if(buttonId = 'action1') {
// action1 was pressed
} else {
// action2 was pressed
}
$('#form').trigger('submit'); // trigger submit of form.
e.preventDefault();
});
First of, never include two dom elements with the same id on the same page. The class attribute is for such things. Change the id's of the buttons to submitButton1 and submitButton2 respectively and then this ought to work:
$('#submitButton1').closest('#form').submit(function() {
// first button action
});
$('#submitButton2').closest('#form').submit(function() {
// second button action
});
For standard HTML form submission :
HTML:
<form method="..." action="...">
...
<input type="hidden" name="action">
<input value="action1" type="submit" value="action 1" />
<input value="action2" type="submit" value="action 2" />
...
</form>
Javascript:
$('button[type="submit"]').on('click', function() {
$("#action").val(this.value);//where "#action" selects an input field (in the same form) of type="hidden"
});
For AJAX submission, do the same but read the action field's value back into javascript in the submit handler.

Categories

Resources