Javascript Function in MVC - javascript

I am developing an Quiz Application in MVC 5. I have added two tables in database. One for marks and other for Questions and Answers. I have entered data in database for question, answers and have entered bool value as true or false for correct answer and vice versa. I am able to view Question and Answers from database.But I got stuck whenever user checks the checkboxes i want to give him points based on correct or wrong answer. I am not able to write javascript function in order to check whether the checkbox is checked or not.
Javascript:
function scorecheck(id) {
if (document.getElementById(id).checked) {
document.getElementById(id).value = "false";
}
else {
document.getElementById(id).value = "true";
}
}
Razor view:
#using(Html.BeginForm("Score", "Home", FormMethod.Post))
{
foreach (var item in Model) {
#Html.DisplayFor(modelItem => item.Question)
#Html.CheckBox("ans1", new { onchange = "scorecheck()" })
#Html.DisplayFor(modelItem => item.ans1)<br />
#Html.CheckBox("ans2", new { onchange = "scorecheck()" })
#Html.DisplayFor(modelItem => item.ans2)<br />
#Html.CheckBox("ans3", new { onchange = "scorecheck()" })
#Html.DisplayFor(modelItem => item.ans3)<br />
#Html.CheckBox("ans4", new { onchange = "scorecheck()" })
#Html.DisplayFor(modelItem => item.ans4)<br />
}
<input type="Submit" value="Submit" />
}
Also I have written logic for giving points for correct and wrong answer but it is not working.
C#:
int s = 0;
string ans1 = c["ans1"];
if (ans1 == "true")
{
s = s + 20;
}
string ans2 = c["ans2"];
if (ans2 == "false")
{
s = s - 20;
}
string ans3 = c["ans3"];
if (ans3 == "false")
{
s = s - 20;
}
string ans4 = c["ans4"];
if (ans4 == "false")
{
s = s - 20;
}

Here is how you can check the value of checkbox on click:
<input type="checkbox" value="yourvalue" onclick="MyFunc(this)">
and the javascript function:
function MyFunc(control)
{
if(control.checked==true)
//your logic
}

I have used following to get id from checkboxes:
`<input id="#(item.ans1)" type="checkbox" name="ans1" value="#item.ans1" onchange="scorecheck('#(item.ans1)')" /> `
Then I am using Javascript Function to check if its value is true or false like this:
if (document.getElementById(id).checked) {
document.getElementById(id).value = "True";
}
else {
document.getElementById(id).value = "False";
}

Related

Coding beginner needing assistance

I'm brand new to coding. I've created a form with three fields- two with "number" types and one with radio button selection. I'm trying to utilize "try catch throw" to validate these fields and have error messages echoed onto the screen (not as an alert). I know that there is a lot of code in here, but I am really lost with this. Here is my HTML and js:
HTML:
<form>
<fieldset>
<label for="hshld" class="formhdr">Total number of people in your household:</label>
<input type="number" id="hshld" name="hshld" min="1">
</fieldset>
<fieldset>
<label for="hrrisk" class="formhdr">Number of high-risk people in your household:</label>
<input type="number" id="hrrisk" name="hrrisk" min="0">
</fieldset>
<fieldset>
<legend class="formhdr">Number of weeks in isolation:</legend>
<input type="radio" id="countone" name="headcount">
<label for="countone" class="numweeks">1</label>
<input type="radio" id="counttwo" name="headcount">
<label for="counttwo" class="numweeks">2</label>
<input type="radio" id="countthree" name="headcount">
<label for="countthree" class="numweeks">3</label>
<input type="radio" id="countfour" name="headcount">
<label for="countfour" class="numweeks">4+</label>
</fieldset>
<input type="submit" value="Submit" id="submit">
</form>
and my .js:
//Global variables
var hshld = document.getElementById("hshld");
var mysubmit = document.getElementById("submit");
var radioError = document.getElementById("radioError");
var weekCount;
//this function checks to see if the user entered a number into the field
function validatehshld() {
try {
if (hshld.value == "") {
throw "Enter a number!";
}
hshld.style.outline = "none";
// clear input box
}
catch (hshldError) {
hshld.style.outline = "2.5px dashed red";
hshld.placeholder = hshldError;
return false;
}
}
// makes sure that the radio button is selected. If not, throws an error message into the "radioError" paragraph at under the form.
function validatewkCount() {
try {
if (weekCount == 0) {
throw document.getElementById('radioError').innerHTML = "Select a number!";
}
// clear input box
hshld.style.outline = "none";
}
catch (weekCountError) {
radioError.style.outline = "2.5px dashed red";
radioError.placeholder = radioError;
return false;
}
}
// stop the form from submitting if a field needs attention
function endEvent() {
return event.preventDefault();
}
function validateSubmit() {
if(validatehshld() === false && validatewkCount() === false) {
endEvent();
}
}
// EventListeners, includes IE8 compatibility
if (hshld.addEventListener) {
hshld.addEventListener("focusout", validatehshld, false);
} else if (hshld.attachEvent) {
hshld.attachEvent("onclick", validatehshld);
}
// runs validateSubmit() function when the user clicks the submit button
if (mysubmit.addEventListener) {
mysubmit.addEventListener("click", validateSubmit, false);
} else if (mysubmit.attachEvent) {
mysubmit.attachEvent("onclick", validateSubmit);
}
if (mysubmit.addEventListener) {
mysubmit.addEventListener("click", numBottles, false);
} else if (mysubmit.attachEvent) {
mysubmit.attachEvent("onclick", numBottles);
}
// this function gets called via the onclick attribute (line 44)
function numBottles() {
// takes the current value of the input field from id "hshld"
var people = document.getElementById("hshld").value;
var hrrisk = document.getElementById("hrrisk").value;
// this variable represents the number of gallons a single person should have for one week of isolation- 1 gallon per day
var weekWater = 7;
// this variable will hold the number of weeks selected from the radio buttons
var weekCount;
// this code determines which radio button is selected and assigns a value to the variable depending on which radio button is selected
if (document.getElementById('countone').checked) {
var weekCount = 1;
} else if (document.getElementById('counttwo').checked) {
var weekCount = 2;
} else if (document.getElementById('countthree').checked) {
var weekCount = 3;
} else if (document.getElementById('countfour').checked) {
var weekCount = 4;
} else if (isNaN(weekCount) === true) {
var weekCount = 0;
}
// echo out the calculation (people X weekWater) to the span object with id=bottles
document.getElementById("bottles").innerHTML = (people * weekWater * weekCount) + (hrrisk * weekCount);
}
Try not to use try, catch, or throw here, instead create your error message in a new element and place it in the html somewhere you think it looks nice.
I would just use:
if (typeof hshld.value !== 'number') { // if a wrong data type was entered
document.getElementById("error-zone").innerHTML += "<div>Enter a number!</div"
} else {
// continue calculating answer
}
for the quick and dirty method.

How to remove an object of an array in javascript by checking checkbox

I have two inputs by type checkbox :
<input type="checkbox" value="5da1dc651d011c56ef1cb3db_693715" onchange="handleChange(this)">
<input type="checkbox" value="6da1dc651d011c56ef1cb3db_837154" onchange="handleChange(this)">
I want to make an array of value of input when it will be checked and when checked is false the object that has that value will be removed , but it would not be removed
var Array = [];
var obj = {};
function handleChange(elem) {
var check = $(elem).prop("checked");
if (check == true) {
obj["obj"] = $(elem).val();
optionalservices.push(obj)
} else if (check == false) {
optionalservices = optionalservices.filter(function (item) {
return item.obj !== $(elem).val();
})
}
}
You can do something like this:-
let selectedValuesArr = [];
function handleChange(event) {
const isChecked = event.target.checked;
if(isChecked) {
selectedValuesArr.push(event.target.value);
} else {
selectedValuesArr.splice(selectedValuesArr.indexOf(event.target.value), 1);
}
}
You can also do like this with little more Optimization
let selectedValuesArr = [];
function handleChange(elem) {
elem.checked ? selectedValuesArr.push(elem.value) : selectedValuesArr.splice(selectedValuesArr.indexOf(elem.value), 1);
}
You can use .map() only on the checked check boxes with .get()
function handleChange() {
var check = $(':checked').map((i, c) => ({sid: c.value})).get();
console.log(check);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="5da1dc651d011c56ef1cb3db_693715" onchange="handleChange()">
<input type="checkbox" value="6da1dc651d011c56ef1cb3db_837154" onchange="handleChange()">

Validating different types of form inputs with criterias

I want to get the answers to a form upon submission and parse them to JSON.
This works quite good but I want some validation before sending the data.
I tried a lot of variations of the snippet down below but am still stuck.
Steps:
Prevent default event on "send"
Get Form
Iterate through the elements of the form
Eliminate empty items and their value
If checkbox is checked: value = true
Store correct items in data
Return data
Somehow I can't get to work steps 4 and 5 work at the same time, every time I get one of them to work I screw over the other one.
In this snippet, the checkbox works as intented but the textfield doesn't:
If anybody can point me in the right direction with the if/else statements or something like that it would be greatly appreciated.
document.addEventListener('DOMContentLoaded', function(){
var data = {};
var formToJSON = function formToJSON(form) {
var data = {};
for (var i = 0; i < form.length; i++) {
var item = form[i];
//looking for checkbox
if (item.value =="") {
continue;
}
else {
if (item.checked == false) {
data[item.name] = false;
}
else {
data[item.name] = item.value;
}
}
}
return data; };
var dataContainer = document.getElementsByClassName('results__display')[0];
form = document.getElementById('formular').querySelectorAll('input,select,textarea');
butt = document.getElementById('knopfabsenden');
butt.addEventListener('click', function (event) {
event.preventDefault();
handleFormSubmit(form = form);
});
var handleFormSubmit = function handleFormSubmit(event) {
var data = formToJSON(form);
dataContainer.textContent = JSON.stringify(data, null, " ");
}
}, false);
<div id="formular">
<label class="formular__label" for="machineName">Textfield Test</label>
<input class="formular__input formular__input--text" id="machineNumber" name="machineNumber" type="text"/>
<br>
<input class="formular__input formular__input--checkbox" id="checkTest" name="checkTest" type="checkbox" value="true"/>
<label class="formular__label formular__label--checkbox" for="checkTest">Checkbox Test</label>
<br>
<button class="formular__button" id="knopfabsenden" type="submit">Submit</button>
</div>
<div class="results">
<h2 class="results__heading">Form Data</h2>
<pre class="results__display-wrapper"><code class="results__display"></code></pre>
</div>
The problem is .checked will always be false if it doesn't exist. So the text field gets the value false.
for (var i = 0; i < form.length; i++) {
var item = form[i];
//looking for checkbox
if (item.value ==="") {
continue;
}
else {
if (item.type === "text") {
data[item.name] = item.value;
}
else if (item.type === "checkbox"){
data[item.name] = item.checked;
}
}
}
In this code snippet I check the type of the input and handle it accordingly. also notice I use the === operator and not the == operator as a best practice (Difference between == and === in JavaScript)

jquery to submit form only after condition is valid and display alert if not

I have this jQuery code. I want to find out what is causing the alertify.error() to displayed as many times as it executes foreach loop to find the sum of the value of text box. Can somebody help me here.
$(document).ready(function() {
$("form").submit(function(e) {
e.preventDefault();
var sum = claculateTotal();
if ($("#TotalWeigh").val() != sum) {
alertify.error('Total weigh should be equal to the sum of weigh of all leaf quality.');
return false;
} else {
this.submit();
}
});
function claculateTotal() {
var sum = 0;
$('.leafWeigh').each(function() {
sum += Number($(this).val());
});
return sum;
}
});
And i have my html code for text boxes as below:
for (int i = 0; i < Model.boughtWeighingModel.Count(); i++)
{
<tr>
<td>
#Html.TextBoxFor(model => Model.boughtWeighingModel[i].LeafQaualityWeight,
new { #class = "form-control leafWeigh" })
</td>
</tr>
}
Why do you really need a <form> element?
HTML
<input name="" />
<button id="submit">Submit</button>
JS
submit.onclick = function(){
// validate and do some ajax...
}

Javascript validation - group validation - if one entered, then all required

Using just jQuery (not validation plugin) I have devised a way to do a "if one, then all" requirement, but it's not at all elegant.
I'm wondering if someone can come up with a more elegant solution? This one uses some loop nesting and I'm really not pleased with it.
if ($("[data-group]")) {
//Store a simple array of objects, each representing one group.
var groups = [];
$("[data-group]").each(function () {
//This function removes an '*' that is placed before the field to validate
removeCurError($(this));
var groupName = $(this).attr('data-group');
//If this group is already in the array, don't add it again
var exists = false;
groups.forEach(function (group) {
if (group.name === groupName)
exists = true;
});
if (!exists) {
var groupElements = $("[data-group='" + groupName + "']");
var group = {
name: groupName,
elements: groupElements,
trigger: false
}
group.elements.each(function () {
if (!group.trigger) {
group.trigger = $(this).val().length !== 0;
}
});
groups.push(group);
}
});
//Now apply the validation and alert the user
groups.forEach(function (group) {
if (group.trigger) {
group.elements.each(function () {
//Make sure it's not the one that's already been filled out
if ($(this).val().length === 0)
// This function adds an '*' to field and puts it into a
// a sting that can be alerted
appendError($(this));
});
}
});
You don't have to store the groups in an array, just call the validateGroups function whenever you want to validate the $elements. Here is a working example http://jsfiddle.net/BBcvk/2/.
HTML
<h2>Group 1</h2>
<div>
<input data-group="group-1" />
</div>
<div>
<input data-group="group-1" />
</div>
<h2>Group 2</h2>
<div>
<input data-group="group-2" value="not empty" />
</div>
<div>
<input data-group="group-2" />
</div>
<div>
<input data-group="group-2" />
</div>
<button>Validate</button>
Javascript
function validateGroups($elements) {
$elements.removeClass('validated');
$elements.each(function() {
// Return if the current element has already been validated.
var $element = $(this);
if ($element.hasClass('validated')) {
return;
}
// Get all elements in the same group.
var groupName = $element.attr('data-group');
var $groupElements = $('[data-group=' + groupName + ']');
var hasOne = false;
// Check to see if any of the elements in the group is not empty.
$groupElements.each(function() {
if ($(this).val().length > 0) {
hasOne = true;
return false;
}
});
// Add an error to each empty element if the group
// has a non-empty element, otherwise remove the error.
$groupElements.each(function() {
var $groupElement = $(this);
if (hasOne && $groupElement.val().length < 1) {
appendError($groupElement);
} else {
removeCurError($groupElement);
}
$groupElement.addClass('validated');
});
});
}
function appendError($element) {
if ($element.next('span.error').length > 0) {
return;
}
$element.after('<span class="error">*</span>');
}
function removeCurError($element) {
$element.next().remove();
}
$(document).ready(function() {
$('button').on('click', function() {
validateGroups($("[data-group]"));
});
});
You might get some milage out of this solution. Basically, simplify and test your solution on submit click before sending the form (which this doesn't do). In this case, I simply test value of the first checkbox for truth, and then alert or check the required boxes. These can be anything you like. Good luck.
http://jsfiddle.net/YD6nW/1/
<form>
<input type="button" onclick="return checkTest()" value="test"/>
</form>
and with jquery:
checkTest = function(){
var isChecked = $('input')[0].checked;
if(isChecked){
alert('form is ready: input 0 is: '+isChecked);
}else{
$('input')[1].checked = true;
$('input')[2].checked = true;
}
};
//create a bunch of checkboxes
$('<input/>', {
type: 'checkbox',
html: 'tick'
}).prependTo('form');
$('<input/>', {
type: 'checkbox',
html: 'tick'
}).prependTo('form');
$('<input/>', {
type: 'checkbox',
html: 'tick'
}).prependTo('form');

Categories

Resources