How to do a Validation Using Jquery- Using .netcore - html

I have an academy platform where the section assessment test is a combination of the following type of questions
Single Answer ( radio button)
Multiple choice ( checkbox)
True or false ( radio button)
reorder ( where I have listed the answers as a drop-down)
I have initialized the following on to the final assessment view:
We are trying to achieve that a user should be able to answer the question as well as at the same time the answer should be validated/checked.
If the user has the right answer to the question then they can move to the next section.
Currently, we are trying to achieve the above-said goal by using the below jquery
var checkedValues = [];
$('.next').click(function() {
var $form = $(this).parent().parent();
var $checked = $(this).parent().parent().find('input[type=radio]:checked')
var isChecked = $checked.length > 0;
if(!isChecked){
alert('Please Choose an option.');
return;
}
checkedValues.push($checked.val());
console.log($checked.val());
$form.hide().next().show(); //hide parent and show next
});
$('.back').click(function() {
console.log('back');
$(this).parent().parent().hide().prev().show(); //hide parent and show previous
});
However, we are unable to achieve to move the user to the next section and also validate the answer. can anyone please help?
PS I have already tried the fieldset method but it does not work in terms of validation and moving to sections. Sections are dynamic. We have to make sure that a user should answer the section assessment before moving to the next section.

Related

Control OnChangeAction default and revert to default when dynamically adding Widget to Google Add-on card

Starting a new question to extend Dynamically Add Widget on user click in Gmail Add-on using CardService Appscript (GAS)
I was able to get this to work on a fairly complex UI card I am designing.
There are two things that I can't seem to control:
The selector after OnChangeAction reverts to the default item, so the user looses the context of their selection. Is there a way to persist the selection when rebuilding the card?
There is no way to setup that the value of the default selected item to force an OnChangeAction event to push its value to the UI on the cards initial load.
Anyone able to use this method to accomplish the above?
I came up with a hack for this that seems to work.
I added a default item to the top of the item list with a label of item0
.addItem("Click here to select an existing item to edit","item0", true)
I also created a cache to cache this label. CacheService.getUserCache().put('itemSelected','item0')
When the item is selected from the dropdown I update the Cache with that items value, e.g. item(n).
I then set up two Widgets within a single function itemManagerCard(e, item) that takes the item I want to change as a parameter.
WidgetOne is the base state of the card where the parameters are undefined
if(item === undefined)
WidgetTwo responds when onModeChange(e) returns the target card with the item parameters I want to change
return itemManagerCard(e, item);
if(item != undefined)
I can then populate WidgetTwo with whatever UI data I want to collect through the function's parameters. Such as:
var editItemNumText = 'You are currently editing ${itemNum}'
function itemManagerCard(e, item) {
var selectItemBodyWidget = CardService.newSelectionInput()
.setType(CardService.SelectionInputType.DROPDOWN)
.setTitle('Which item do you want to edit?')
.setFieldName('editItem');
.setOnChangeAction(CardService.newAction().setFunctionName('onModeChange'))
.addItem("Click here to select an existing Item to edit","item0", true)
.addItem("Item 1","item1", false);
//
if (item != undefined)
let itemNum = CacheService.getUserCache().get('itemNum');
var itemText = `You are currently editing ${itemNum}`;
var itemWidget = CardService.newTextParagraph()
.setText(itemText);
}
function onModeChange(e) {
let itemNum = (e.formInput.editItem);
CacheService.getUserCache().put('itemNum', itemNum);
var item = itemArr[itemNum]
return itemManagerCard(e, item);
}
Major drawback is needing to build and maintain the two separate virtually identical Widgets, which can get messy the more complex it gets.

how to toggle appended elements using multiple buttons and pass info to the output JQuery

I have asked kind of a similar question before : how to toggle using multiple buttons and pass info to the output JQuery
It was answered well, but this time I am using a different approach in the code thus a new question.
I am trying to toggle info and append a div using three different buttons.
Here is The code https://jsfiddle.net/YulePale/nruew82j/40/
JavaScript
document.getElementById("brazil").addEventListener('click', function(e){
if(e.currentTarget.dataset.triggered) return;
e.currentTarget.dataset.triggered = true;
AppendFunction();
function AppendFunction() {
var para = document.createElement("p");
var homeTeam = document.getElementById("brazil").value
para.innerHTML = 'This is the national team of ' + `${homeTeam}` + ':'
<br> <input type="text" value="${homeTeam}" id="myInput"><button
onclick="myFunction()">Copy text</button>';
var element = document.getElementById("gugu");
element.appendChild(para)
}
})
document.getElementById("draw").addEventListener('click', function(e){
if(e.currentTarget.dataset.triggered) return;
e.currentTarget.dataset.triggered = true;
AppendFunction();
function AppendFunction() {
var para = document.createElement("p");
var homeTeam = document.getElementById("draw").value
para.innerHTML = 'This two teams have played each other 4 times ' +
`${homeTeam}` + ':' <br> <input type="text" value="${homeTeam}" id="myInput">
<button onclick="myFunction()">Copy text</button>';
var element = document.getElementById("gugu");
element.appendChild(para)
}
})
document.getElementById("russia").addEventListener('click', function(e){
if(e.currentTarget.dataset.triggered) return;
e.currentTarget.dataset.triggered = true;
AppendFunction();
function AppendFunction() {
var para = document.createElement("p");
var homeTeam = document.getElementById("russia").value
para.innerHTML = 'This is the national team of ' + `${homeTeam}` + ':'
<br> <input type="text" value="${homeTeam}" id="myInput"><button
onclick="myFunction()">Copy text</button>';
var element = document.getElementById("gugu");
element.appendChild(para)
}
})
PS: I don't know why the javascript code is not working in fiddle yet it is working on my computer.
If you look at the code I am basically trying to toggle a div with info on various teams. If it is Brazil the div comes with info on Brazil if Russia, info on Russia.
The problem with my current code is that it keep on appending the divs instead of
toggling them. How can I toggle them? like this: https://jsfiddle.net/YulePale/7jkuoc93/
Instead of having them append another div each time I click a different button?
............................................................................................
PS: EDIT & UPDATE:
#Twisty, I forked the code from your fiddle and tried to implement it when working with more than one row of buttons. The code works well but I was unable to append a different and separate element for each row each time I click on a button on that row.
I tried putting the appended element as a class:
Here is the code: https://jsfiddle.net/YulePale/a9L1nqvm/34/
Also tried putting it as an id:
Here is the code: https://jsfiddle.net/YulePale/a9L1nqvm/38/
How can I put it in a way that each row appends it's own separate element and I would also like users to be able to copy using the copy button without the element disappearing. How do I make it in such a way that the element only disappears only when I click outside the respective:
<div class="col.buttonCol " id="buttons-div">
and also disappears when I click another row of buttons?
Also in your answer you said you would have used text boxes instead of appending this way. I checked the modals out and they all appear on the browser like alerts can you please point me to a resource that show how you can use a modal that works like an appending element instead of one that acts as an alert? Thank you.
Here is the link to the modals I saw: https://getbootstrap.com/docs/4.0/components/modal/
I converted all your JavaScript to jQuery since you posted this in the jquery-ui, I am assuming you want to work with jQuery.
I will often organize my functions first and then the interactive actions.
JavaScript
$(function() {
function myFunction() {
//Do Stuff
}
function AppendFunction(id) {
var para = $("<p>");
var home = $("#" + id).val();
para.append("This is the national team of " + home + ":", $("<br>"), $("<input>", {
type: "text",
value: home,
id: "myInput"
}), $("<button>").html("Copy Text").click(myFunction));
$("#gugu").html(para);
}
function emptyOnDocumentClick(event) {
var action = $(".triggered").length;
$(".triggered").removeClass("triggered");
return !action;
}
$("#brazil, #russia").on('click', function(e) {
if ($(this).hasClass("triggered")) {
return;
}
$(this).addClass("triggered");
var myId = $(this).attr("id");
AppendFunction(myId);
});
$(document).on("click", function(e) {
if (emptyOnDocumentClick(e)) {
$("#gugu").html("");
}
});
});
Working Example: https://jsfiddle.net/Twisty/nruew82j/91/
The basic concept here is a dialog and if it were me, I would use a dialog box either from BootStrap or jQuery UI. You're not doing that, so we're create the content and append it to a specific <div>. Then, like in your previous question, you just detect a click on the document and decide what that will do. In this case, I emptied the content of the <div> that we'd previously appended content to.
Hope that helps.

Is that any option for search tabs in chrome?

that is we have opened many tabs.In that tabs i want to search specific tab. Please tell if any ext or option or add-on in chrome or firefox.
Firefox has this functionality built in. If you just start typing in the URL bar and the first character you type is % followed by a space, the rest of what you type will be treated as a search on the titles and urls of open tabs in all Firefox windows.
I'm not sure if this is the site to be asking for help finding extensions that do end user tasks such as this so I'll answer your question explicitly as well as explain how to do it programatically.
The short answer is, yes one extension that will allow you to do this can be found here:
Tab Title Search
The long answer is, in order to find all tabs with a certain name, you need to use the chrome tabs API
I whipped up a short piece of javascript to demonstrate how to have an extension that will create a popup with a search box that you type the desired tab title into. If the tab is found, it will be listed below the search box. If you click on the listing, you will switch to the tab.
// Function to search for tabs
function searchtabs() {
chrome.tabs.query({
title: ""
},
// Callback to process results
function(results) {
// Place holder for the tab to process
var foundTab = null;
// Text to match against
var queryText = document.getElementById("textToSearchInput").value;
// Div to place divs of matched title in
var queryAnswerDiv = document.getElementById("foundTabsDiv");
// Clear the current children
while (queryAnswerDiv.hasChildNodes()) {
queryAnswerDiv.removeChild(queryAnswerDiv.lastChild);
}
// Iterate over all the results
for (var i = 0; i < results.length; i++) {
// Keep track of the tab that is currently being processed
foundTab = results[i];
// If we have a title containing our string...
if (foundTab.title.indexOf(queryText) > -1) {
// Create a new div
var tabDiv = document.createElement("div");
// Set its content to the tabs title
tabDiv.innerHTML = foundTab.title;
// Let it know what the tabs id is
tabDiv.tabToSwitchTo = results[i].id;
// Allow for users to click on the representing div to switch to it
tabDiv.onclick = function() {
// Make the tab selected
chrome.tabs.update(this.tabToSwitchTo, {
selected: true
});
};
// Append the created div to our answer div
queryAnswerDiv.appendChild(tabDiv);
}
}
});
}
document.addEventListener('DOMContentLoaded', function() {
var inputField = document.getElementById("textToSearchInput");
inputField.focus();
inputField.onkeydown = searchtabs;
});
Also, if this is more what you are looking for rather than the extension that I linked, let me know and I can pack this extension.
Edit:
Fixed an error in using the wrong ID to get the input field as well as not getting the first letter of the title (use indexOf() > -1)
An extension that does this is Tab Hero for Chrome ($0.99 Chrome extension). It searches through all of the open tabs (across multiple windows) and offers to switch to the filtered tab. Try and see if it works for you.

taking values separately using local storage in html5

I am making an app in html5.It is like a quiz based app. I am randomly fetching questions from the XML and displaying it one by one.I am using page navigation for that. After completing and submitting your answer u will switch to other page.if once i submit my answer i cannot attempt it back. but i can see the feedback and score on switching to that page that is my problem. I have display that feedback and score and to store it in local storage. i am able to do local storage but values that i am getting is overriding. so i am getting last submitted value.Now my concern is to divide that values navigation number wise.right now what is happening if i submit my answer and suppose i am at navigation number 3 n i am looking at navigation part 1 then there also i am getting last submitted value not the part 1 value.Please give ur suggestion and help me out for that.
Here is the code snippet:
//for navigation of pages
$(document).ready(function (){
/*$(document).bind("contextmenu",function(e){
return false;
});*/
var obj;
total=x.length;
for(var j=0;j<x.length;j++)
{
if(j==0)
{
$("#navigationlist").append('<li>'+(j+1)+'</li>');
display_nav(j,$("#selected_link"))
}
else
$("#navigationlist").append('<li>'+(j+1)+'</li>');
}
$("#next").bind("click",function (){
$(".navg").each(function(index){
if($(".navg").length==(i+1))
{
if(index==0)
obj=$(this);
}
else
{
if(index==(i+1))
obj=$(this);
}
});
for(var j=0;j<xmlDoc.getElementsByTagName("question").length;j++)
{
xmlDoc.getElementsByTagName("question")[j].removeAttribute("status");
}
$("#btnSubmit").attr("disabled","false");
$("#btnSubmit").attr("onclick","checekAnswer()");
display_nav(0,obj)
}
else
display_nav((i+1),obj)
});
});
and
correctAnswers++;
localStorage.setItem('feedback',JSON.stringify(feedback[0].childNodes[0].nodeValue));
$("#feedback").append(score[0].childNodes[0].nodeValue);
$("#feedback").append("<br/>");
$("#feedback").append(feedback[0].childNodes[0].nodeValue);
}
else
{
//var val = [];
//val.push(feedback[0].childNodes[0].nodeValue);
//localstorage.setItem('feedback', JSON.stringify(val));
//localStorage.setItem('feedback',JSON.stringify(feedback[0].childNodes[0].nodeValue));
//alert(localStorage.getItem("feedback"));
/*var v={"test":feedback[0].childNodes[0].nodeValue};
localStorage.setItem('feedback',v);
alert(localStorage.getItem('feedback'));*/
scores1.push(feedback[0].childNodes[0].nodeValue);
localStorage.setItem("highscores",JSON.stringify(scores1));
var scores = localStorage.getItem("highscores");
alert(scores);
scores = JSON.parse(scores);
alert(scores[0]);
$("#feedback").html(score[1].childNodes[0].nodeValue);
$("#feedback").append("<br/>");
$("#feedback").append(feedback[0].childNodes[0].nodeValue);
$("#feedback").append("hello");
}
//$("#counter").html("left="+xPos+",top="+yPos);
$("#trFeedBack").show("slow");
display_nav(j,obj)
}
} // end function
If I understand your question, your problem is to store items with same name but related to different pages.
LocalStorage being defined by domain, and not by page, you must change the keys you use. The usual solution is to prefix the names you want.
For example :
localStorage['pages.12.feedback'] = "the feedback I'm giving related to page 12";
localStorage['global.feedback'] = "the feedback I'm giving related to the global site";
(you'll notice I use the short notation, that I find more readable that using setItem)

How to: Update jQuery dialog div with new content from json

I am attempting to update the div of my dialog with new content from a json array and am encountering issues and am requesting some guidance.
I output a json array which has labels for a 'Name' and a 'Definition'. A user is presented with a list of radio buttons. When a user clicks a radio button which has the following structure:
<input type="radio" value="23" name="statistic" id="stat-23" />
I take the value of the radio button and use this to identify which 'Name' 'Definition' pair I am referring to from my json array.
I then use the 'Name' 'Definition' pair to populate a div which typically updates dynamically. To accomplish this I use the following code:
$('input[type=radio]').live( 'change', function(){
if ( ! $(this).is(':checked') )
return false;
var stat_id = $(this).attr( 'id' ).replace( /stat-/, '' );
refreshDefinition( stat_id );
} );
function refreshDefinition( stat_id ) {
var definition = definitions[ stat_id ];
var div = $("<div id='definition'>"+definition.name+": "+definition.definition+"</div>");
$('#definition').replaceWith( div );
}
This works fine without a dialog (it updates just fine as is), however, it would look a lot better if there were some way to incorporate a dialog so that when a user clicks a button, the dialog will appear and they can see the 'Name' 'Definition' pair and then can exit out of it when they are satisfied.
$('#definition').dialog();
I would like the above code to show the updated data, but it does not appear to allow it.
If you have any guidance on how I could go about solving this problem or any alternative approaches, I would really appreciate it!
Thanks.
Have you tried updating the dialogs content?
$('#definition').html(definition.name+": "+definition.definition);
Here's an example.
EDIT:
unnecessary .dialog('widget') made this answer wrong.