Below code redirect user by selecting option from the sub categories.
How can I store/remember their choice of selection in LocalStorage and redirect users automatically in their next visit & create a button which clears localstorage if user wants to change the category?
Here's the
screenshot of the output
function fillCategory(){
// this function is used to fill the category list on load
addOption(document.drop_list.Category, "Fruits", "Fruits", "");
addOption(document.drop_list.Category, "Games", "Games", "");
addOption(document.drop_list.Category, "Scripts", "Scripts", "");
}
function SelectSubCat(){
// ON selection of category this function will work
removeAllOptions(document.drop_list.SubCat);
addOption(document.drop_list.SubCat, "", "SubCat", "");
if(document.drop_list.Category.value == 'Fruits'){
addOption(document.drop_list.SubCat,"Mango", "Mango");
addOption(document.drop_list.SubCat,"Banana", "Banana");
addOption(document.drop_list.SubCat,"Orange", "Orange");
}
if(document.drop_list.Category.value == 'Games'){
addOption(document.drop_list.SubCat,"Cricket", "Cricket");
addOption(document.drop_list.SubCat,"Football", "Football");
addOption(document.drop_list.SubCat,"Polo", "Polo", "");
}
if(document.drop_list.Category.value == 'Scripts'){
addOption(document.drop_list.SubCat,"PHP", "PHP");
addOption(document.drop_list.SubCat,"ASP", "ASP");
addOption(document.drop_list.SubCat,"Perl", "Perl");
}
}
//////////////////
function removeAllOptions(selectbox)
{
var i;
for(i=selectbox.options.length-1;i>=0;i--)
{
//selectbox.options.remove(i);
selectbox.remove(i);
}
}
function addOption(selectbox, value, text )
{
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}
///////////////////
function SelectRedirect(){
// ON selection of Sub category this function will work
//alert( document.drop_list.SubCat.value);
switch(document.drop_list.SubCat.value)
{
case "PHP":
window.location="../php_tutorial/site_map.php";
break;
case "ASP":
window.location="../asp-tutorial/site_map.php";
break;
case "Perl":
window.location="../sql_tutorial/site_map.php";
break;
/// Can be extended to other different selections of SubCategory //////
default:
window.location="../"; // if no selection matches then redirected to home page
break;
}// end of switch
}
Related
I want to make a history search based on user text input html, this code below works fine but it duplicates the same input. For instance :
The user type 'abcd' in input text and click the button.
the value 'abcd' store as history search.
When the user try to search the 'abcd' and click the button again, the history search adding 'abcd' as well, so it has 2 'abcd' value.
My js function:
function cek() {
resi_or_code = document.getElementById('code_or_resi').value;
resi = resi_or_code.split(',');
if($.trim(resi_or_code) != ''){
location.href = base_url + 'resi/' + encodeURIComponent(resi_or_code);
}
if (localStorage.daftar_data){
daftar_data = JSON.parse(localStorage.getItem('daftar_data'));
$("#riwayat").toggle();
}
else {
daftar_data = [];
}
for (y in daftar_data){
var q = daftar_data[y].resis;
for (x in resi){
console.log(q);
if (q === resi[x])
{
console.log('Value exist');
}else{
console.log('Value does not exist');
daftar_data.push({'resis':resi[x]});
localStorage.setItem('daftar_data', JSON.stringify(daftar_data));
}
}
}
}
What did I do wrong? Please help.
Call to the count function made by two group of checkboxes. First group represents categories, when clicked subjects for that category will be listed out.
html: id: counter displays count value. id: select replaces text acordingly
<div class="small-8 text-left columns" style="left:-30px;">
<span id="counter"><span id="count">0</span></span>
<span id="select">Select Subjects</span>
</div>
script:(categories group) To pass value for the subjects to be fetched by ajax. updateCount();is the count function call.
$("input[type=checkbox][id^=level]").change(function() {
var selectedval = $(this).val();
if($(this).is(":checked")) {
var selectedtext = $(this).next().text();
sendtobox(selectedval, $("#slider1").val(),"regis");
} else {
$("th."+selectedval).remove();
updateCount();
}
});
(subjects group)
$(document).on('change', '[id^=sub][type=checkbox]', updateCount);
count function:
function updateCount () {
$('#count').text($('[id^=sub][type=checkbox]:checked').length);
}
script to replace text:
$(".close-reveal-modal").on("click",function()
{
document.getElementById("select").innerHTML = "Select subject";
var str = document.getElementById("select").innerHTML;
var res = str.replace("Select subject", "Selected Subject");
document.getElementById("select").innerHTML = res;
});
Now I can replace text and the count works just fine! My problem is it doesn't obey the English grammar!
If 0 item/subjects returned, the text should be 0 Selected Subjects and if more than 1 is checked, it should say the same. See the (s) must be added in 'subject' word.
My problem is , I couldn't identify number of counts to replace this text.
I want someting like this:
if ($("#count") >1 || ($("#count")==0))
{
var res = str.replace("Select subject", "**Selected Subjects"**);
document.getElementById("select").innerHTML = res;
}
else
{
var res = str.replace("Select subject", "**Selected Subject"**);
document.getElementById("select").innerHTML = res;
}
I tried to alert $('#count').length , it red like this each time the checkbox checked:
1 1 1 1
What I'm expecting is
1 -when clicked once
2 - when clicked twice
This way would be easier for me to replace text indeed!
it sounds like you want the TEXT of the span with id 'count' for that comparison:
if ($("#count").text() == "1") {
// singular
}
else {
// plural
}
I'm trying to make a quiz powered by jQuery (and maybe JSON), with the values stored in a database. It works fine so far, but I'd like to hide the radio buttons (CSS: display: none) and make each question look like a button (much easier to select than a tiny radio button).
However, when I do this, the following JavaScript doesn't work, and the quiz isn't scored.
var imgpath = "/images/sections/test/";
var jsonpath = "/2b/inc/pages/quiz-php/json/";
var jsonfile = "key";
$(document).ready(function(){
//Make sure radio buttons are not disabled or checked (helpful when refreshing)
$("input[type='radio']").attr("disabled", false);
$("input[type='radio']").attr("checked", false);
$(".submit").click(function(e){
e.preventDefault();
//Check the quiz results
checkQuiz();
});
//Build the json filename
jsonfile = $("#quiz").attr("rel")+".php";
});
//Load json file
function getData(update){
$.getJSON(jsonpath+jsonfile, function(json){
//Execute the callback
update(json);
}).error(function(){alert("error");});
}
function checkQuiz(){
$(".submit").remove();
getData(function(data){
var ans = data.key;
var result = {};
$(".Question").each(function(){
//Get the question id
var _q = $(this).attr("id");
//Get the selected answer class
var _a = $("#"+_q+" input:checked").closest("li").attr("class");
//Add the values to the result object
result[_q] = _a;
//Compare the selected answer with the correct answer
if(ans[_q]==_a){
$(this).addClass("correct");
}else{
$(this).addClass("wrong");
}
});
//Build the feedback
var fdbck = "You got "+$(".correct").length+" out of "+$(".Question").length+" correct. "
if($(".correct").length==0){
fdbck += "Better luck next time.";
}else if($(".correct").length>$(".Question").length/2){
fdbck += "Good job!";
}else{
fdbck += "Not bad.";
}
$(".feedback").text(fdbck);
$(".feedback").show();
});
}
So I wondered if there's some way to record scores besides a radio button. I created a JSFiddle # http://jsfiddle.net/9j7fz99w/6/ to illustrate how I'm using jQuery and CSS to style correct and incorrect answers. Is there a way to modify the code above to similarly recognize correct questions based on their "selection," rather than a radio button?
Just a small example using a JS questions Array with Objects
var $quizEl = $("#quizEl");
var $submit = $("#submit");
var quiz = [
{ // obj
"Q" : "What color is the Sun?",
"A" : ["Red", "Black", "Yellow"],
"C" : 2
},{
"Q" : "What color is an Elephant?",
"A" : ["Gray", "Blue", "Yellow"],
"C" : 0 // zero indexed!
},{
"Q" : "What color is the Sea?",
"A" : ["Fuchsia", "Blue", "Gold"],
"C" : 1
}
];
var qNum = quiz.length;
// FUNCTION THAT CREATES AND APPENDS AN `UL` TO `DIV #quizEl`
function generateQuestion( obj, idx ) {
var html = "<h2>"+ obj.Q +"</h2><ul>";
for (var i=0; i<obj.A.length; i++) {
html += "<li>"+
"<label>"+
"<input type='radio' name='"+ idx +"' value='"+i+"'>"+
obj.A[i] +"</label>"+
"</li>";
}
$quizEl.append( html+"</ul>" );
}
// GENERATE ALL QUESTIONS:
for(var i=0; i<qNum; i++) {
generateQuestion( quiz[i], i ); // quiz[i] is the {QAC} object
}
$quizEl.on("change", ":radio", function(){ // Record User choice (U property)
quiz[this.name].U = this.value; // set 0,1,2 to the new U property {QACU}
});
$submit.on("click", function(e){
e.preventDefault();
console.log( quiz ); // To test how it looks
// Check if user answered them all:
for(var i=0; i<qNum;i++){
if(!quiz[i].hasOwnProperty("U")){ // User did not answered if "U" property doesn't exists
return alert("Please,\nanswer the question "+ (i+1) +":\n"+ quiz[i].Q );
}else{ // Add classes...
$("ul").eq(i).find(":checked").closest("li")
.addClass( +quiz[i].U === quiz[i].C ? "correct":"wrong");
}
}
// Finally colour them!
$(".correct").css({background:"green"});
$(".wrong").css({background:"red"});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="quizEl"></div>
<input id="submit" type="submit">
In my entity (A) has 50 option set. If the user select 10 optionsset value and not selected remaining one, and he/she click save button. In that situation i need to alert user "To fill all the option set". I don't want to get the Schema name for the optionset individually, i need to get all the option set schema name dynamically.
Is it possible? Help me.
I have not tested this function, but you can try this and make changes if needed.
function IsFormValidForSaving(){
var valid = true;
var message = "Following fields are required fields: \n";
Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
if (attribute.getRequiredLevel() == "required") {
if(attribute.getValue() == null){
var control = attribute.controls.get(0);
// Cheking if Control is an optionset and it is not hidden
if(control.getControlType() == "optionset" && control.getVisible() == true) {
message += control.getLabel() + "\n";
}
valid = false;
}
}
});
if(valid == false)
{
alert(message);
}
}
Ref: Microsoft Dynamics CRM 2011 Validate required form javascript
Required fields individual alert fire before the on save event. If you wish to prevent the single alert routine for all unfilled option sets you need to remove the requirement constraint and manage the constraint yourself, probably in your on save handler. I’m just writing the idea here (not tested).
// enter all optionsets ids
var OptionSets50 = ["new_optionset1","new_optionset2","new_optionset50"];
var dirtyOptions = [];
function MyOptionSet(id) {
var mos = this;
var Obj = Xrm.Page.getAttribute(id);
var Ctl = Xrm.Page.getControl(id);
Obj.addOnChange(
function () {
if (Obj.getValue() != null)
delete dirtyOptions[id];
else
dirtyOptions[id] = mos;
});
this.GetLabel = function() {
return Ctl.getLabel();
}
if (Obj.getValue() == null)
dirtyOptions[id] = mos;
}
function OnCrmPageLoad() {
for(var x in OptionSets50) {
OptionSets50 [x] = new MyOptionSet(OptionSets50 [x]);
}
Xrm.Page.data.entity.addOnSave(OnCrmPageSave);
}
//check for dirty options and alert
function OnCrmPageSave(execContext) {
var sMsg = "The following Optinsets Are Required: ";
var sLen = sMsg.length;
for(var os in dirtyOptions) {
sMsg += dirtyOptions[os].GetLabel() + "\n";
}
if (sMsg.length > sLen) {
execContext.getEventArgs().preventDefault();
alert(sMsg);
}
}
I am new to Dojo and working with someone else's code. Currently, this function looks to see the value of a dropdown box. Based on that value, it adds another form box, on the fly, for a user to fill out. In all the examples I have, I've only seen the function create one added form box. In a particular case, though, I'd like to add a second row with another form box. I thought maybe repeating the line twice would do the trick, but it doesn't. Any thoughts how to do this? Thanks in advance...
Switch Statement:
if (form_row != null)
dojo.destroy(form_row);
//Add the correct new field to the form.
switch (inquiry.selectedIndex) {
case place_order:
html = this.create_form_row(id, "Account Number");
break;
case order_status:
html = this.create_form_row(id, "Order Number");
break;
case telalert_signup:
html = this.create_form_row(id, "Account Number");
break;
case invoice_questions:
html = this.create_form_row(id, "Invoice Number");
break;
case new_option:
html = this.create_form_row(id, "Invoice Number");
(WANT TO CREATE A SECOND ROW HERE!)
break;
default:
}
Function being called:
create_form_row: function(id, label) {
//Container
var a = dojo.create("div", { id: id, className: "question", style: "padding-top:4px;" });
//Label
var b = dojo.create("div", { className: "label", innerHTML: label, style: "margin-top:8px;" }, a);
//Field
var c = dojo.create("div", { className: "field" });
var d = dojo.create("span", { className: "full_number_span span" });
var e = dojo.create("input", { type: "text", className: "textbox acct_num", name: label }, d);
dojo.place(d, c);
dojo.place(c, a);
return a;
}
If you tried
case new_option:
html = this.create_form_row(id, "Invoice Number");
html = this.create_form_row(id, "SOMETHING ELSE");
break;
it wouldn't work because you would just overwrite the html variable and throw away the first one.
You can either change stuff so that html is supposed to be a list of nodes or you can try wrapping your two form nodes inside a single one
var html = dojo.create('div');
dojo.place(this.create_form_row(...), html);
dojo.place(this.create_form_row(...), html);