JavaScript/jQuery Class modification - javascript

I'm trying to change the state of a button (using Bootstrap) from active to inactive based on input from the user. In the bigger picture, I am trying to come up with an intuitive way to test input for a form, so that once every field is valid, the submit button can then be pressed for PHP processing on the server side. Here is what I currently have for code:
<br>
<label>
Input: <input type="text" name="sample" class="form-control" id="input" onkeyup="activateButton()" required>
</label>
<br>
<label>
<button type="submit" name="submit" class="btn btn-success disabled" id="button">Submit</button>
</label>
<script type="text/javascript">
function activateButton() {
"use strict";
var input = document.getElementById("input").val();
if (input == "activate") {
document.getElementById("button").className = "btn btn-success active";
}
}
</script>
This is, of course within html markup, and so I wanted to get some pointers on how to approach this, since my current setup doesn't seem to work. Thank you!

In your code document.getElementById("input").val(); should be document.getElementById("input").value;
And Since you have tagged question in jquery too..
function activateButton() {
"use strict";
var input =$("#input").val();
if (input == "activate") {
$("#button").toggleClass("btn btn-success active");
}
}
ADDITION(extra info asked by the user):
$("input").keyup(function(){
var d=$(this).val();
var res = d.test(/your-regex-here/);
if(res)
{
//enable button here
}
else
{
//disable button here
}
});

Related

How to check if an entered answer is correct with HTML code?

I'm developing an escape room game for my students in Google Sites, and I have a problem with de HTML code.
The goal is to enter a text answer in a text box and then check whether that answer is correct or not. If not correct, a message should appear warning this and the continue button should not be enabled; while in case the answer was correct, a message should appear congratulating them and unlock the button to continue.
I made a first version of the HTML code (see below) but it doesn't work for me, as I have problems in the if section.
Could someone please help me solve this? I am a science teacher, a novice in programming and due to COVID-19 I would like to implement something different for my students.
Thank you very much in advance!
<head>
<title></title>
<script>
function checkAnswers(){
Student_answer = document.f1.Student_answer.value
Teacher_answer = "abc"
if (Student_answer.length == 0 || Teacher_answer.length == 0) {
alert("You must enter an answer to continue...");
return false;
}
if (Student_answer == Teacher_answer) {
alert("CONGRATULATIONS! Your answer is correct! You have advanced to the next level");
//<button onclick="window.location.href = 'https://www.google.com';">Next Riddle</button>
//NOTE: here is where the button should be activated and click on it to advance to an hyperlink
}
else
{
alert("Worng answer, please, keep trying...<br />");
//NOTE: here the button must be disabled
}
}
</script>
</head>
<body>
<h3>Write here your answer...</h3>
<br>
<form action="" name="f1">
Youy answer: <input type="password" name="clave1" size="20">
<br>
<br>
<input type="button" value="Check" onClick="checkAnswers()">
</form>
</body>
</html>```
This works.
<html>
<head>
<title></title>
<script>
function checkAnswers(){
// The following is what I changed.
Student_answer = document.querySelector('[name="clave1"]').value
Teacher_answer = "abc"
if (Student_answer.length === 0 || Teacher_answer.length === 0) {
alert("You must enter an answer to continue...");
return false;
}
if (Student_answer === Teacher_answer) {
alert("CONGRATULATIONS! Your answer is correct! You have advanced to the next level.");
document.body.innerHTML += '<button onclick="window.location.href = \'https://www.google.com\';">Next Riddle</button>'
//NOTE: here is where the button should be activated and click on it to advance to an hyperlink
} else {
alert("Wrong answer, please, keep trying...");
//NOTE: here the button must be disabled
}
}
</script>
</head>
<body>
<h3>Write here your answer...</h3>
<br>
<form action="" name="f1" onsubmit >
Your answer: <input type="password" name="clave1" size="20">
<br>
<br>
<input type="button" value="Check" onClick="checkAnswers()">
</form>
</body>
</html>
I also made some grammar and style fixes in your code.
Edit: I added the button functionality you asked about in your comment.
you just have a small issue in your HTML, while reading input with JS
Considering this HTML
<h3>Write here your answer...</h3>
<br>
<form name="f1">
Your answer: <input type="password" name="studentAnswer" size="20">
<br>
<br>
<input type="button" value="Check" onClick="checkAnswers()">
</form>
I've edited the name of the input, as you need to "select" it from JS using the name. So as you can see the input name is now studentAnswer, and that's how you reference it in your JS code, which I've edited as following
function checkAnswers() {
// document.$formName.$inputName
Student_answer = document.f1.studentAnswer.value
Teacher_answer = "abc"
if (Student_answer.length == 0 || Teacher_answer.length == 0) {
alert("You must enter an answer to continue...");
return false;
}
if (Student_answer == Teacher_answer) {
alert("CONGRATULATIONS! Your answer is correct! You have advanced to the next level");
//<button onclick="window.location.href = 'https://www.google.com';">Next Riddle</button>
//NOTE: here is where the button should be activated and click on it to advance to an hyperlink
} else {
alert("Worng answer, please, keep trying...<br />");
//NOTE: here the button must be disabled
}
}
I've kept it simple to avoid confusing you, great idea you had imho
Change,
Student_answer = document.f1.Student_answer.value
to
Student_answer = document.getElementsByName('clave1')[0].value
You can use getElementsByName() and get element via name attribute and can get the value..
function checkAnswers(){
Student_answer = document.getElementsByName('clave1')[0].value
Teacher_answer = "abc";
const form = document.querySelector('form');
if (Student_answer.length == 0 || Teacher_answer.length == 0) {
alert("You must enter an answer to continue...");
return false;
}
if (Student_answer == Teacher_answer) {
alert("CONGRATULATIONS! Your answer is correct! You have advanced to the next level");
form.innerHTML +=
`<button onclick="window.location.href = 'https://www.google.com';">Next Riddle</button>`
//NOTE: here is where the button should be activated and click on it to advance to an hyperlink
}
else
{
alert("Worng answer, please, keep trying...<br />");
//NOTE: here the button must be disabled
}
}
<h3>Write here your answer...</h3>
<br>
<form action="" name="f1">
Youy answer: <input type="password" name="clave1" size="20">
<br>
<br>
<input type="button" value="Check" onClick="checkAnswers()">

Toggle visibility of buttons on forgotten required form fields

I have several forms on my profile page. Each form has its own submit button. When a user clicks the submit button, I want the button to disappear and show a spinner.
That works fine. The issue that I am running into, is that if the user forgets to fill-out a required field, the button does not return visible. The spinner stays visible. And the page would have to be reloaded.
Jquery is not intercepting the form submission (though I am open to that if it will fix the issue), it is only toggling the spinner and button visibility.
Any help?
$("#profile-loading").hide();
$("#social-loading").hide();
$(document).ready(function () {
$("#btn_profile").on("click", function (e) {
$("#profile-loading").show();
$("#btn_profile").hide();
checkForm('#formProfile', "#btn_profile", "#profile-loading");
});
$("#btn_social").on("click", function (e) {
$("#social-loading").show();
$("#btn_social").hide();
checkForm('#formSocialMedia', "#btn_social", "#social-loading");
});
});
//Check the passed in form and toggle the buttons and the loading spinner
function checkForm($formid, $buttonid, $spinnerid) {
var emptyFields = $('#formProfile .required').filter(function () {
return $(this).val() === "";
}).length;
if (emptyFields === 0) {
console.log("no emptyFields");
} else {
console.log("emptyFields");
return false;
}
//I tried looping through each form field, but can't seem to get the form targeted.
// $($formid + '.required').each(function () {
// console.log("checkForm");
//
// var self = $(this)
// if (self.val() === '') {
// // empty
// console.log("empty");
// } else {
// // not empty
// console.log("NOT empty");
// }
// });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="somelink" id="formProfile">
<input id="name" name="name" type="text" required="required">
<input id="url" name="url" type="text" required="required">
<i class="fas fa-spinner fa-2x fa-spin" id="profile-loading"></i>
<button id="btn_profile" type="submit">Save Changes</button>
</form>
<form method="post" action="someotherlink" id="formSocialMedia>
<input id="facebook" name="facebook" type="text" required="required">
<input id="instagram" name="instagram" type="text" required="required">
<i class="fas fa-spinner fa-2x fa-spin" id="social-loading"></i>
<button id="btn_social" type="submit">Save Changes</button>
</form>
There are several issues with your code, but the most important one is that you are retrieving required form elements using a required class, which does not seem to be used in your html. Instead, you can retrieve required form elements using something like
$('#formProfile [required]')
which returns all subelements of formProfile which have the required attribute. You have another issue in that the id of the form is hard-coded. Instead of hard-coding it, use the variable $formid.
$($formid + ' [required]')
Try reordering your scripts, do validation first and check if it's pass. Make sure the checkForm returns true if valid.
$("#btn_profile").on("click", function (e) {
if (checkForm('#formProfile', "#btn_profile", "#profile-loading")) {
$("#profile-loading").show();
$("#btn_profile").hide();
}
});
$("#btn_social").on("click", function (e) {
if (checkForm('#formSocialMedia', "#btn_social", "#social-loading")) {
$("#social-loading").show();
$("#btn_social").hide();
}
});

Unable to dynamically set a Input of type check box as required using javascript/jQuery

I am working on a sharepoint 2013 edit aspx form. now I have the following checkbox:
<span title="Yes" class="ms-RadioText">
<input id="UpdateOrder_0e0052d6-9924-4774-b50d-d7ef364d744a_MultiChoiceOption_0" required="" type="checkbox">
<label for="UpdateOrder_0e0052d6-9924-4774-b50d-d7ef364d744a_MultiChoiceOption_0">Yes</label>
</span>
now I want under certain conditions to set this checkbox as required, so users can not submit the form unless they check this checkbox. so I wrote the following javascript:
var orderstatus0 = $('select[id^="OrderStatus_"]').val();
if (orderstatus0 == "Invoiced")
{
$('input[id^="UpdateOrder_"]').required;
var x = document.getElementById('UpdateOrder_0e0052d6-9924-4774-b50d-d7ef364d744a_MultiChoiceOption_0').required;
document.getElementById('UpdateOrder_0e0052d6-9924-4774-b50d-d7ef364d744a_MultiChoiceOption_0').required= true;
alert(x);
}
but currently no validation will be applied, even inside the alert i was excepting to get true, but I am getting false.. so can anyone advice on this please?
Add the code below into a script editor web part in the editform page.
<script src="//code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
function PreSaveAction(){
var orderstatus0 = $('select[id^="OrderStatus_"]').val();
$("#updateordermsg").remove();
if (orderstatus0 == "Invoiced"){
if($('input[id^="UpdateOrder_"]').is(':checked')){
return true;
}else{
$('input[id^="UpdateOrder_"]').closest("td").append("<span id='updateordermsg' style='color:red'><br/>Please check the UpdateOrder.</span>");
return false;
}
}else{
return true;
}
}
</script>
You should use .att() jQuery function to set the attribute to the element.
var orderstatus0 = $('select[id^="OrderStatus_"]').val();
$('input[id^="UpdateOrder_"]').attr("required", "required");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<span title="Yes" class="ms-RadioText">
<input id="UpdateOrder_0e0052d6-9924-4774-b50d-d7ef364d744a_MultiChoiceOption_0" type="checkbox">
<label for="UpdateOrder_0e0052d6-9924-4774-b50d-d7ef364d744a_MultiChoiceOption_0">Yes</label>
</span>
<input type="submit" value="Submit">
</form>

Bootstrap jQuery - Issues with empty field validation

I've written some jQuery to validate my Bootstrap forms, however I'm having a few issues.
Firstly, I want a red outline to appear if the user clicks off the input field without typing anything in: JSFiddle example here. In this example I'm using the Bootstrap Validator plugin, however I want to imitate this effect without using the plugin.
Second, and linked to the issue I just mentioned, the green outline only appears once the user clicks the submit button, thus the user only sees it for half a second or so before they are redirected, making it a little pointless. Again, this would be solved by having an error/success outline appear once the user clicks off the input. If anyone could help me out it would be greatly appreciated.
This is the code I have so far:
HTML:
<form id="auth_form" action="action.php" method="post">
<div class="form-group has-feedback" name="auth_code" id="auth_code">
<label for="auth_code" class="control-label">
Authorisation Code</label>
<input class="form-control" id="auth_code_input" name="auth_code_input" type="password">
<span class="form-control-feedback glyphicon" id="iconBad"></span>
</div>
<div class="form-group">
<div>
<button class="btn btn-info" name="submit" type="submit" id="submit">Submit</button>
</div>
</div>
</form>
jQuery:
$(document).ready(function() {
$('#auth_form').on('submit', function(e) {
var auth_code = $('#auth_code_input').val()
if (auth_code=="") {
$('#auth_code').addClass('has-error');
$('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove');
e.preventDefault();
} else {
$('#auth_code').removeClass('has-error').addClass('has-success');
$('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok');
}
})
})
JSFiddle
Try this updated fiddle: jsfiddle.net/xqwsobmo/20/
Need to add input blur event and validate input
$(document).ready(function() {
$('#auth_code_input').blur(function(){
if(!ValidateInput()){
e.preventDefault();
}
});
$('#auth_form').on('submit', function(e) {
if(!ValidateInput()){
e.preventDefault();
}
})
});
function ValidateInput(){
var IsValid=false;
var auth_code = $('#auth_code_input').val()
if (auth_code=="") {
$('#auth_code').addClass('has-error');
$('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid=false;
} else {
$('#auth_code').removeClass('has-error').addClass('has-success');
$('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid=true;
}
return IsValid;
}

Radio buttons checked changing submit text

My site structure consists on an index.php which is styled by a css file. It then includes the following php code in a separate file:
<?php include("globals.php"); ?>
<form action="<?php echo $website.$relative_string;?>" name="subscribe" onsubmit="javascript:return checkEmail(this);" method="post">
<div id="cell8" class="titlecell2"><h3>Email:</h3></div>
<div id="cell9" class="inputcell2">
<input type="text" class="inputfield2" name="email" value="Your Email..." id="email2" maxlength="255" onfocus="this.value='';">
</div>
<div id="cell10" class="textcell3">
<input name="group" type="hidden" id="group[]" value="<?php echo $group; ?>">
<input name="subscribe" id="sub" type="radio" value="true" checked>
</span>Subscribe </p>
</div>
<div id="cell11" class="buttoncell">
<button type="submit" name="Submit2" value="Join" id="submitButton2">
<span>OK</span>
</button>
</div>
<div id="cell8" class="textcell4">
<input type="radio" name="subscribe" id="unsub" value="false">
</span>Un-Subscribe </p>
</div>
</form>
It appears on screen with no problems in the correct layout as my css style sheet. What I would like this to do is when I select the "Subscribe" radio button the submit button text "OK" changes to "Join". When I click on the Unsubscribe button text "OK" or "Join" changes to "Leave".
I tried to make some code from research:
if(document.getElementById('sub').checked) {
document.write("<span>Join</span>"
}
else if(document.getElementById('unsub').checked) {
document.write("<span>Leave</span>)
}
I think this kind of worked in that it changed to Join (replacing the OK line, but obviously didn't update on clicking unsubscribe. I guess it would update on refreshing the page if my default wasn't join. I guess I need to do some form of onclick but then I have no idea how to adjust that span ok bit.
Please help?
Many thanks Chris
Here is a solution in plain JavaScript without jQuery. It avoids the unnecessary overhead.
This should work, but I haven't had a chance to test it:
var sub = document.getElementById('sub'); // Save element to a variable, so you don't have to look for it again
var unsub = document.getElementById('unsub');
var btn = document.getElementById('submitButton2');
sub.onchange = function() //When sub changes
{
if(sub.checked) //If it's checked
{
btn.innerHTML = "<span>Join</span>"; // Set button to Join
}
else // If not..
{
btn.innerHTML = "<span>OK</span>"; // Set button to OK
}
}
unsub.onchange = function() //When unsub changes
{
if(unsub.checked) //If it's checked
{
btn.innerHTML = "<span>Leave</span>"; // Set button to Leave
}
else // If not..
{
btn.innerHTML = "<span>OK</span>"; // Set button to OK
}
}
However, you should not do it like this.
You should combine the two radio buttons into a radio group.
In that case you will listen for radio group to change, get the value of the radio group, set button text according to the value.
if you label your <span>OK</span> to something like <span id="your_id">OK</span> then added a class to your radio button like this <input class="your_class" type="radio" name="subscribe" id="unsub" value="false"> them...
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$("#your_class").change(function () {
if ($(this).is(':checked')) {
$("#your_id").text('Join');
}else {
$("#your_id").text('Leave');
}
});
</script>
This was all written in the browser so let me know if there are any problems.

Categories