Select a valid choice. '"xxx" is not one of the available choices - javascript

I know many people have been asking this question "Select a valid choice. 'xxx' is not one of the available choices." but I just think my scenario is somewhat different.
Well, what I was trying to do is; I have an input choice field that allow someone to choose between two choices (Let's say choices are A and B). Hence if someone decides to choose choice A; some of available input fields will disappear while holding default values that i have assigned to them (this is to allow form submission. I can't make them required=False since if you choose choice B, this input fields will appear and if required=False they may be submitted without values.Something that I don't want):
forms.py
cars = forms.ModelChoiceField(queryset = cars.objects.all(),widget=Select(attrs={'class': 'form-control seleckpicker','required':'True'}),empty_label="Choose car") . Hence if it return empty list if nothing in table. So what I was trying to do is append value.
under html page
$('select[name=fuel] option:eq(1)').attr('selected', 'selected');
$('#id_cars').append($('', {
value: 'AA',
text: 'AA',
}));
$('id_total_fruits').val(0);
So what I was trying to do is append value to id_cars incase the dropdown is empty field
This is why I decided to append value to be able to submit my though; even though doing this makes me getting this error:
"Select a valid choice. 'xxx' is not one of the available choices."
I hope I make myself clear. Anyone with solution please...????

I may be misunderstanding the question a bit here, so if im way off base let me know and i'll delete my answer haha.
why not do an if or switch block statement switched based on the selections to set the required attribute
ie.
`$('#selector').on('change', function() {
if ($(this).val() == "A")) {
$('#inputA').prop('required', true);
$('#inputB').removeAttr('required');
}
if ($(this).val() == "B")) {
$('#inputB').prop('required', true);
$('#inputA').removeAttr('required');
}
});
Thats what i have used on some of my pages in this scenario.

Related

How to copy the value of a yform to an other field

In our (hybris) shop some products have a yform to summarize the parts of the product. Is there an easy way to copy the value of the sum field into an other field (automaticly) like the productquantity (no yForm)?
I guess I need javascript, but the id of the sumfield is generatad, so I don't know how to get the sum. Also my Javascript abilities are quite limited...
UPDATE:
To get the value I use this part of code:
copyYFormValueToProductQuantity : function() {
var copyText = document.querySelector('input[id*="sum"]').value
if (copyText > 0 && copyText != null)
{
//do stuff
}
console.log("Copied value: " + copyText)
},
But this line
document.querySelector('input[id*="sum"]').value
returns null. If I use it in the browserconsole, it also returns null. But after I inspected the element it works and returns the value I want to. So I guess I am missing some JS-basics here and the object isn't ready before?
Btw.: I call this function with a keydown-eventlistener.
This can most likely be done from the jsp files. There you have all the data that is needed, so you most likely need to only copy that field where you need it.
We can also help you more if you add some code examples here (what exactly is that yform?). If you struggle to find where in code is that specific yform created/added, it's always worth giving a try to search for the applied classes of the html (search the entire project and see what you find).
As I understand your question, you are saying that you want to copy the value of a yForm field named sum into a non-yForm field named productquantity, and you are asking specifically about how to access the value of a yForm field from JavaScript. If I understand this correctly, you can do so by calling the following JavaScript API:
ORBEON.xforms.Document.getValue("sum");
You can find more about this and other related API on Client-side JavaScript API.

Is it possible to assign a code block to a switch case twice in Javascript?

I have some Javascript that is processing a form to send the results to the server through Ajax, and I want to reuse from code to process common components of certain question types. Let's say I have two question types "Forced Choice" and "Forced Choice with Other", both of which use radio buttons to force the user to choose one option, but in the second type, a radio button labeled "other" will allow them to input their own answer into a question box. Getting the radio button value will be common between the two but getting the "other" value will not. Would it be acceptable to say
switch(questionType) {
case 'Forced Choice':
case 'Forced Choice with Other':
//code to get radio button value
case 'Forced Choice with Other':
//if value was "other", get the value of the textbox
break;
default:
break;
}
or would it be preferable to say
switch(questionType) {
case 'Forced Choice':
case 'Forced Choice with Other':
//code to get radio button value
if(val == 'other' && questionType == 'Forced Choice with Other')
//code to get "other" value
break;
default:
break;
}
Edit: I just wanted to add some clarification that in my actual code, the question type distinction is not as simple as with or without allowing "other". I'd like to use the same code to get the value of all radio-button based questions, and there are several types. For some, it would be as simple as getting the values, but for others, my script would have to check how to script is configured in the form's JSON configuration file. I'd like to use the first pattern to avoid a chunk of several if statements that all have 2-3 conditions.
Which pattern do you think is preferable and why (if the first pattern would even function correctly)?
In Javascript, like in a lot of common languages, switch cases "fall through" to the next one unless broken explicitly with a break statement. This means that your first example would work, technically, but it's terrible practice, very confusing to read and to maintain (also, I wouldn't be surprised if the duplicate label confused some interpreters or code analyzers).
It's probably best to just extract the common functionality into named functions. This would make your code the easiest to read and maintain, and the repetition would be reduced to calling the same function twice.

Variable checking in JSP

I am fairly new to the JSP scene, but have been programming in other languages for a few years. I am writing an application where I am passing a different variable to java based on a selection option. My main question was where to do the variable checking to see which value to pass?
Here is my current state of value checking (I am currently rewriting it in JSTL as I found sciplets are bad practice).
if (request.getParameter("Freq").equals("Minutes")) {
runOn = request.getParameter("numberOfMinutes");
} else if (request.getParameter("Freq").equals("Weekly")) {
runOn = request.getParameter("dayOfWeek");
} else if (request.getParameter("Freq").equals("Monthly")) {
runOn = request.getParameter("dayOfMonth");
} else {
runOn = "-1";
}
Should this sort of check be done on the jsp page, in javascript, or somewhere else? Looking for a best practice kind of answer.
Side question: Right now, I create a number of different drop down boxes and hide/unhide them using an onChange function in javascript. Would it be better to have one list box where the options change in javascript or keep the current system? Essentially the list boxes are asking the user what day they want their process to run. So if frequency is weekly, a list box with the days of the week would show, but if they have month selected, a list of numbers from 1 to 31 shows. It could all be done with one list box that changes its options when the 'frequency' drop down changes. Again, I'm looking for a best practice answer?
Thank you in advance!

Check for correct answer (quiz) using PHP and AJAX

I have a picture quiz with a single input field for each image. I need a way to check if the value entered into the input field matches the correct answer and if it does, perform a few operations like add/remove a few CSS classes and increase the score count. And I need this to be done in real time using AJAX.
This is the pseudo-code for the functionality that I want...
if input value == correct answer {
some jQuery to add/remove a few classes
some PHP (I assume) to add 1 to the score count
} else {
some jQuery to add/remove a few classes
}
However, how do I get the value of the input field in real time? Do I still use PHP Post to get the value? What AJAX do I need to do this without a page refresh?
Any help would be greatly appreciated... I'm okay with PHP but very little experience with AJAX. Thank you.
yes this can be done with AJAX, and with jquery (which is not the same).
You can get input string with $("#input_id").val() , show a simple error message with alert("my message"), and use the onchange event. see also what is e.preventDefault() to make the form not submitable if all is not correct
If you want to check if datas are correct with a php request, that's also possible with $.ajax()
See jquery documentation on the web for further information about all theses functions
In case this is useful for anyone else, this is how I achieved my original goal. Contrary to what I first thought, this can all be done using JS and does not require PHP or AJAX to update in real time.
$('input').keyup(function () {
if (($(this).val() == 'test') {
//Stuff
} else {
//Other Stuff
};
});
The .keyup() function is what allows this to work in real-time, as it is called whenever a key is hit on your keyboard.
Then within this, the .val() function is what is used to check the actual user-entered value of the input field. In this case, if this value equals 'test', then it performs whatever you place in the if statement.
Hope that helps if anyone has stumbled across this question hoping for this answer!

Default Value in drop down list not being selected

I have a drop down list [ Incident, Question, Problem, Task]. I have written a code when an end user logins in and has a tag called product the default value should be problem. However it does not seem to work. It still gives the user the option to select values from the list.
$j(document).ready(function() {
if(location.pathname == '/requests/new') {
var ct = currentUser.tags;
if(ct.indexOf("product") >= 0){
$j(document.getElementById("ticket_fields_75389").value = "Problem");
}
else {
$j(document.getElementById("ticket_fields_75389").value = "");
}
}
})
Note: This answer is incorrect. I will delete it once I know the OP read my comment.
It still gives the user the option to select values from the list.
Well, of course, setting value will only change the initially selected value. If you want "fix" the value of the select element, so that the user cannot change it, you have to make it read-only. Lets stick with jQuery (what you have is a weird mix of DOM API and jQuery †):
$j("#ticket_fields_75389").val("Problem").prop('readonly', true);
†: Let's have a close look at the line
$j(document.getElementById("ticket_fields_75389").value = "Problem");
What exactly is happening here? Obviously we have a function call ($j(...)) and we pass something to it. This "something" is the result of the expression
document.getElementById("ticket_fields_75389").value = "Problem"
This finds an element by ID and assigns the string "Problem" to the value property. This is an assignment expression. The result of an assignment expression is the assigned value, i.e. "Problem".
That is the value that is passed to $j(...), so we have $j("Problem");. Since $j refers to jQuery, this would search for all elements with tag name Problem, which does not exist in HTML. It would also return a jQuery object, but you are not doing anything with it.
Hence the wrapping in $j(...) is completely unnecessary or even wrong, even though it doesn't throw a syntax or runtime error.

Categories

Resources