Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to use select to give users a option of two things. 1 option is owner the other option is is non owner. i want to be able to ask them different questions if they are owner or not. i want them to be able to enter there answers numerically 1-10, and give them feedback based on the answers. ill try to make it super clear if i can. one question with two options. when that is selected the owner or non owner questions will be asked and added i have include a fiddle with what i have. I am all over the place, and have no idea don't mind me. if someone can show me on that works that would be great!!! change anything in it, just want it to work. http://jsfiddle.net/philyphil/CcVsz/11/
<select class="myOptions">
<option data-val="" selected>Pick an option</option>
<option data-val="owner">Owner</option>
<option data-val="not-owner">Not Owner</option>
</select>
I'd suggest, to handle the summation, changing the jQuery to:
$('#butt').click(function () {
/* this gets an array of the numbers contained within visible
input elements */
var nums = $('.list input:visible').map(function () {
return parseInt(this.value, 10);
}),
// initialises the total variable:
total = 0;
/* iterates over the numbers contained within the array,
adding them to the 'total' */
for (var i = 0, len = nums.length; i < len; i++) {
total += nums[i];
}
var msg = '';
if (isNaN(total)) {
msg = 'Input three numbers, please...';
} else if (total < 30) {
msg = "That's bad, should be higher...";
} else if (total > 40) {
msg = "That's bad, should be lower...";
} else {
msg = "You got it... Nice work.";
}
$('#output').text(msg);
});
And also not using the id attribute to select the elements to sum, instead using class-names:
<div class="list owner">
<p>a</p>
<input class="numbers" type="text" size="2" />
<br/>
<p>b</p>
<input class="numbers" type="text" size="2" />
<br/>
<p>c</p>
<input class="numbers" type="text" size="2" />
<br/>
<!-- questions for owners -->
</div>
<div class="list not-owner">
<p>x</p>
<input class="numbers" type="text" size="2" />
<br/>
<p>y</p>
<input class="numbers" type="text" size="2" />
<br/>
<p>z</p>
<input class="numbers" type="text" size="2" />
<br/>
<!-- questions for non-owners -->
</div>
JS Fiddle demo.
To test if someone is, or says they are, the owner:
var total = 0,
isOwner = $.trim($('.myOptions option:selected').val()) === 'owner';
if (isOwner) {
console.log("It's the owner");
}
The above jQuery is coupled to a select element in which the option elements have values:
<select class="myOptions">
<option value="-1" data-val="" selected>Pick an option</option>
<option value="owner" data-val="owner">Owner</option>
<option value="not-owner" data-val="not-owner">Not Owner</option>
</select>
JS Fiddle demo.
References:
jQuery.trim().
map().
:selected selector.
:visible selector.
Your selector was wrong inside click handler for 'not owner' btw IDs must be unique on context page. Best way is to use class instead of IDs and check for visible boxes:
$('.myOptions').change(function(){
$('.list').removeClass('active')
.filter('.' + $('.myOptions').children('option:selected').attr('data-val'))
.addClass('active');
});
/* want to say if owner do this
when I un-comment this it breaks
var qbc = $('#owner')
var c = $('#myOptions')
if $(c == qbc){
prompt("worked!!!!")
}
*/
$('#butt').click(function () {
var $boxOne = $('.box:visible').eq(0);
var k1 = parseInt($boxOne.val(), 10);
var $boxTwo = $('.box:visible').eq(1);
var k2 = parseInt($boxTwo.val(), 10);
var $boxThree = $('.box:visible').eq(2);
var k3 = parseInt($boxThree.val(), 10);
var total = k1 + k2 + k3;
var msg = '';
if (isNaN(total)) {
msg = 'Input three numbers, please...';
} else if (total < 30) {
msg = "That's bad, should be higher...";
} else if (total > 40) {
msg = "That's bad, should be lower...";
} else {
msg = "You got it... Nice work.";
}
$('#output').text(msg);
});
/* else i will change question number and do same thing */
DEMO
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a page full of random stuff and into those things I have a random number generator. I tried it but the result is higher than expected, somebody knows what? Here is my code:
<div>
<h2>Get a random number</h2>
<br>
<input type="text" id="inputMin" placeholder="Min" required autocomplete="off">
<input type="text" id="inputMax" placeholder="Max" required autocomplete="off">
<br><br>
<button id="randomNumberButton">Generate</button>
<br>
<span class="error" id="randomNumberError"></span>
<span id="randomNumberResult"></span>
</div>
And the JavaScript:
try {
var randomNumberError = document.getElementById("randomNumberError")
const randomNumberButton = document.getElementById("randomNumberButton")
function getRandomNumber2(){
var inputMin = document.getElementById("inputMin")
var inputMax = document.getElementById("inputMax")
const selector = getRandomNumber(inputMin.value, inputMax.value)
console.log(inputMin.value, inputMax.value, selector);
const result = document.getElementById("randomNumberResult")
function removeRandomNumberError(){
randomNumberError.textContent = ""
}
if (inputMin.value == "" || inputMax.value == ""){
randomNumberError.textContent = "Both fields are required."
inputMin.addEventListener("click", removeRandomNumberError)
inputMax.addEventListener("click", removeRandomNumberError)
return
}
if(isNaN(inputMin.value) || isNaN(inputMax.value)){
randomNumberError.textContent = "Both values should be numbers"
inputMin.addEventListener("click", removeRandomNumberError)
inputMax.addEventListener("click", removeRandomNumberError)
return
}
result.textContent = selector
}
randomNumberButton.addEventListener("click", getRandomNumber2)
} catch (err){
randomNumberError.textContent = err
}
I would really appreciate if someone
You can try this solution (working as I understood to your question):
html code (only changed input type to number)
<input type="number" id="inputMin" placeholder="Min" required autocomplete="off">
<input type="number" id="inputMax" placeholder="Max" required autocomplete="off">
and js code is:
var button = document.getElementById('randomNumberButton');
var result = document.getElementById('randomNumberResult');
button.addEventListener('click', function() {
var min = parseInt(document.getElementById('inputMin').value);
var max = parseInt(document.getElementById('inputMax').value);
result.value = Math.floor(Math.random() * max) + min;
alert(result.value);
});
I have a table with some questions (chosen via <select> elements) and comments (in <textarea> elements) for each question. All questions are required, but I want only a certain number of comments filled in order to submit. I'm generating the comment and question inputs from a table in SQLite, so I can't hard code require anywhere as it would be on all of them. The solution can either be in the Javascript code or the Ruby ERB.
I have a question and comment counter which I'm sure I could use in a solution somehow. I'm pretty new to Javascript, and not sure how to make it work.
This is my attempt at implementing this functionality:
<table class="sortable">
<tr>
<th></th>
</tr>
<% data.each.with_index do |data,index|%>
<%if data[0] >= 6 && data[0] <= 20%>
<tr>
<td><%=data[1]%></td><td><select name="<%=index%>">
<option value=""></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="na">N/a</option>
</select>
<div class="accordion">Comment</div>
<div class="panel">
<textarea class="comments" name="comment<%=index%>" rows="4" cols="15"></textarea>
</div>
</td>
</tr>
<% end %>
<% end %>
</table>
$('select').change(function() {
// get all selects
var allSelects = $('select');
// set values count by type
//var yes = 0;
//var no = 0;
// var na = 0;
var total = 0;
// for each select increase count
$.each(allSelects, function(i, s) {
// increase count
if($(s).val() == 'Yes' ) { total++; }
if($(s).val() == 'No') { total++; }
if($(s).val() == 'na') { total++; }
});
// update count values summary
$('.cnt-yes').text(yes);
$('.cnt-no').text(no);
$('.cnt-na').text(na);
$('.cnt-total').text(total);
if (total > 19) {
alert('You have completed this ......')
};
var commentstotal = 0;
$('select').change(function() {
$('.comment-total').text(commentstotal);
});
$(".comments").on("blur", function(){
$(this).val() ? commentstotal++ : commentstotal--;
$('.comment-total').text(commentstotal);
})
The HTML and Javascript was pretty close to what you wanted, and only minor changes were really required. There were a few missing elements, and some reformatting was done to improve readability and consistency. This jsFiddle named Form comment validation shows the solution in action.
The HTML code (assumes that this exists within a <form> element):
<table class="sortable">
<th>
<td></td>
</th>
<% data.each.with_index do |data,index| %>
<% if data[0] >= 6 && data[0] <= 20 %>
<tr>
<td>
<%=data[1]%></td><td><select name="<%=index%>">
<option value=""></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="na">N/A</option>
</select>
<div class="accordion">Comment</div>
<div class="panel">
<textarea class="comments" name="comment<%=index%>" rows="4" cols="15"></textarea>
</div>
</td>
</tr>
<% end %>
<% end %>
</table>
<fieldset>
<legend>Totals</legend>
<p>Yes choices: <span id="cnt-yes"></span></p>
<p>No choices: <span id="cnt-no"></span></p>
<p>N/A choices: <span id="cnt-na"></span></p>
<p>Total choices: <span id="cnt-total"></span></p>
<p>Comments: <span id="comment-total"></span></p>
<p>Progress: <span id="progress-message"></span></p>
</fieldset>
<input type="submit" value="Submit!">
This includes these changes:
Corrected the use of the <th> element for the table header
Added a <fieldset> to house the counts and progress message
Added the submit button to demonstrate the enable/disable functionality
The Javascript code:
var submit = $("input[type='submit']"); // Submit button (to enable/disable dynamically)
var allSelects = $("select");
var cnt_yes = $("#cnt-yes");
var cnt_no = $("#cnt-no");
var cnt_na = $("#cnt-na");
var cnt_total = $("#cnt-total");
var progress_message = $("#progress-message");
var allComments = $(".comments");
var comment_total = $("#comment-total");
var comments_required = 1; // <== Change this to set the number of comments required
var comment_minimum_length = 8; // <== Change this to set the minimum accepted length of a comment
function process_choice() {
// get all selects
// set values count by type
var count_yes = 0;
var count_no = 0;
var count_na = 0;
var count_total = 0;
var count_comments = 0;
var complete = true;
// for each select increase count
$.each(allSelects, function(i, s) {
// increase count
switch ($(s).val()) {
case "Yes":
++count_yes;
break;
case "No":
++count_no;
break;
case "na":
++count_na;
break;
default:
complete = false;
break;
}
});
count_total = count_yes + count_no + count_na;
$.each(allComments, function() {
count_comments += $(this).val().length >= comment_minimum_length ? 1 : 0;
});
// update count values summary
cnt_yes.text(count_yes);
cnt_no.text(count_no);
cnt_na.text(count_na);
cnt_total.text(count_total);
comment_total.text(count_comments);
if (count_comments < comments_required) {
var count_remaining = comments_required-count_comments
$("#progress-message").text("Only " + count_remaining + " choice" + (count_remaining > 1 ? "s" : "") + " left to complete.");
complete = false;
} else {
$("#progress-message").text("The required number of comments has been satisfied.");
}
if (complete) {
submit.removeProp("disabled");
} else {
submit.prop("disabled","disabled");
}
};
allSelects.change(process_choice);
allComments.blur(process_choice);
process_choice();
The updated Javascript includes these changes:
jQuery selectors moved to the top of the script to cache the results (preferred for static HTML like this)
made the previously anonymous event callback function into a named function for initialization purposes (see the last item)
uncommented and renamed the yes, no, and na variables to demonstrate how to update counts dynamically
changed the if..if..if to a switch statement, as the options are mutually exclusive for a given choice
added the individual totals to count_total for subsequent use
added a minimum accepted length check for comments
added tracking of whether the form is complete, based on whether all choices and the minimum number of comments have been made
updated the totals to the <span> elements in the new <fieldset> display
Updated the progress message to include the number of remaining comments or that the requirements have been satisfied
enabled/disabled the submit button when choices are unselected or too few comments have been made
registered the new named function for the change event
called the new named function on startup to initialize the state of the page, so that the page state is guaranteed to be in-sync from the start
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
If I enter 0900 in this text field then I would like it to automatically turn into 09:00
form
<form action="form.html">
<p>
<label>time:</label>
<input type="text" name="time" class="time"/>
</p>
<span id="error" class="hide">Error in the field</span>
</form>
I Know I should use the following to at least get the value and then I have to turn that value into the value that I want:
$(document).ready(function(){
$(".time").on("focusout",function(){
var old_value = $(this).val();
// The old value to the new value
if(old_value.length < 2 || > 4){
$("#error").show();
} else {
if(old_value.length == 2){
// Then add 2 leading zero's
// Then add a : in the middle
} else if (old_value.length == 3){
// Then add 1 leading zero's
// Then add a : in the middle
} else if (old_value.length == 4){
// Then add a : in the middle
}
}
}
Thanks in advance for the effort taken. If something isn't clear please ask me.
Use this as a basis to solve your problem:
$("#your_filed_id").on("focusout", function(){
// Do whatever checking you like here
});
You can do like this:
JsFiddle: http://jsfiddle.net/ha9kx/1/
HTML:
<form action="demo_form.html">
<p>
<label>Hour:</label>
<input type="text" name="hour" class="hour_modification"/>
</p>
<span id="error" class="hide">Error in the field</span>
</form>
JavaScript:
$(document).ready(function(){
$(".hour_modification").on("focusout",function(){
var old_val = $(this).val();
if (old_val.length > 4 || old_val.length < 3){
$("#error").show();
}
else{
if(old_val.length = 3){old_val = "0" + old_val;}
var new_val = old_val.substring(0,old_val.length-2) + ":" + old_val.substring(old_val.length-2);
$(this).val(new_val);
}
});
});
This solution will work even if the user put "300" for "03:00"
If the entered value is always going to be 4 characters in the format you specified above, the following code should work. I don't use jQuery that often, but the following should give you an idea of what is required. You can modify the event listener with jQuery along with the selector.
http://jsfiddle.net/DS92Z/
<input type="text" id="time" />
<script>
var input = document.getElementById('time');
input.addEventListener('blur',function(e) {
var target = e.target || e.srcElement;
var value = target.value;
if(value.length != 4) {
return false;
}
target.value = value[0]+value[1]+':'+value[2]+value[3];
},false);
</script>
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have the below form with radio buttons and i want to replace them (the 2 options inc no thanks) with simple check boxes - leaving 3 check boxes.
I can't manage to change the JS to get it working... I've tried tweaking the JS but it stops the ability to either calculate or redirect - which is the main form purpose!
Help!
<html>
<head></head>
<body>
<form onSubmit="submitForm();" id="myForm" type="get">
<input type="radio" name="myRadio1" data-op="0" value="10" onClick="calcNow();" selected />Option A
<input type="radio" name="myRadio1" data-op="1" value="120" onClick="calcNow();" />No thanks<br/>
<input type="radio" name="myRadio2" data-op="0" value="10" onClick="calcNow();" selected />Option B
<input type="radio" name="myRadio2" data-op="1" value="20" onClick="calcNow();" />No thanks<br/>
<input id="myCheckbox" name="myCheckbox" type="checkbox" value="10" onClick="calcNow();" />Otion C<br/>
<input id="myTotal" name="myTotal" type="text" value="" disabled="disabled" /><br/>
<input type="button" id="myButton" onClick="submitForm();" value="Continue" />
</form>
<script type="text/javascript">
var pages = [[["http://mysite.com/page1.html","http://mysite.com/page2.html"],["http://mysite.com/page3.html","http://mysite.com/page4.html"]],[["http://mysite.com/page5.html","http://mysite.com/page6.html"],["http://mysite.com/page7.html","http://mysite.com/page8.html"]]];
function calcNow()
{
var cb = document.getElementById("myCheckbox");
var cost1 = getRadioValue("myRadio1");
var cost2 = getRadioValue("myRadio2");
var cost3 = cb.checked ? parseInt(cb.value) : 0;
var costTotal = cost1 + cost2 + cost3;
document.getElementById("myTotal").value = costTotal;
var op1 = getRadioData("myRadio1", "op");
var op2 = getRadioData("myRadio2", "op");
var op3 = cb.checked ? 1 : 0;
if (op1 != undefined && op2 != undefined && op3 != undefined)
{
return pages[op1][op2][op3];
}
return undefined;
}
function submitForm()
{
var page = calcNow();
if (page != undefined)
{
// ---- To popup ----
//alert(page);
// ---- To navigate ----
location.href = page;
// ---- To alter post ----
//var form = document.getElementById("myForm");
//form.action = page;
//form.submit();
}
else
{
alert("Please answer all questions.");
}
}
function getRadioValue(name)
{
var controls = document.getElementsByName(name);
for (var i = 0; i < controls.length; i++) {
if (controls[i].checked) {
return parseInt(controls[i].value);
}
}
return 0;
}
function getRadioData(name, attribute)
{
var controls = document.getElementsByName(name);
for (var i = 0; i < controls.length; i++) {
if (controls[i].checked) {
return parseInt(controls[i].dataset[attribute]);
}
}
return undefined;
}
</script>
</body>
</html>
I suggest for you and I don't your Javascript in you case.
There are two suggest.
You replace on the input radio with two input checkbox.
<input type="checkbox" name="myRadio1" data-op="1" value="on" onClick="calcNow();" />No thanks<br/>
<input type="checkbox" name="myRadio2" data-op="0" value="10" onClick="calcNow();" selected />Option B
This is easy but now it 's difficult.
When the input 's checked, call the function calcNow() but when this is unchecked your can't call the function .
But for the management I suggest that your search on GOOGLE.
For me is better that your add the button that call the function submitForm();
This is a example for checked and unchecked.
EDIT:
I working on your case and there is a solution JSDIFFLE
Declaration: I am not sure if that is a parameter. Please enlighten.
I have a medical questionnaire form with almost 19 yes and no radio buttons.Each question's radio buttons must have a unique input name in order to make it work. I manage to find a suitable code to toggle an text area if the yes radio button is selected however, it can only work in one of the input name and there are 18 more which needs it to be working as well.
My main question is:
function displayTextBox()
{
var objElement = document.getElementById('addmed');
addmed.style.display = 'block';
addmed.style.visibility = 'visible';
}
function hideTextBox()
{
var objElement = document.getElementById('addmed');
addmed.style.display = 'none';
addmed.style.visibility = 'hidden';
}
function validate()
{
var arrElements = document.getElementsByName('medq');
var objElement;
var boolContinue = false;
var objaddmedtext;
for(var i=0, _length=arrElements.length; i<_length; i++)
{
objElement = arrElements[i];
if(objElement.checked)
{
if(objElement.id == 'yes')
{
objaddmedtext = document.getElementById('addmedtext');
if(strTrim(objaddmedtext.value).length>0)
{
boolContinue = true;
break;
}
}
else
{
boolContinue = true;
break;
}
}
}
if(boolContinue)
{
alert('Continue, user completed the information.')
}
else
{
alert('Ask user to complete the data.')
}
}
/**
* Removes all white space characters from the string.
*
* #param: {String} String to trim.
*
* #return {String} Trimed string.
*/
function strTrim(strTrim)
{
return strTrim.replace(/^\s+|\s+$/g, '');
}
Looking at this javascript,a textarea
<div id="addmed" style="display:none;visibility:hidden; margin-left:10px; width:110px;">
<textarea id="addmedtext" cols="60" rows="6" placeholder="Please give details with dates"></textarea>
</div>
will only appear if the yes radio button is selected for
<tr>
<td width="33">1.</td>
<td width="491">Heart or circulatory problems including: high blood pressure, heart attack, angina, heart murmur, heart failure, palpitations, circulatory problemseg. whitefinger, blocked arteries, stroke aneurysm.</td>
<td width="68"><input name="medq" id="yes" type="radio" value="yes" onclick="displayTextBox()"/><label for="yes"> Yes </label></td>
<td width="78"><input name="medq" id="no" type="radio" value="no" onclick="hideTextBox()"/><label for="no"> No </label></td>
However, this is only 1 question...I have 18 more question with name="medq 1 to 18 ".
Any ideas how to edit the javascript to add the parameters??
First, you need to have unique ID on every radio button. But you need the same NAME on each pair of YES/NO button to process the selected one of the pair. So you can have
<input type="radio" name="foo" id="foo_y" value="yes" /><label for="foo_y">Yes</label>
<input type="radio" name="foo" id="foo_n" value="no" /><label for="foo_y">Yes</label>
<textarea id="foo_text" name="foo_text"><textarea>
Now, for the "yes" radio buttons, you can add onclick="displayTextBox( this )". "this" is a pointer to the current radio button.
You can then update the function like so:
function displayTextBox( f ) { // f is the field that was clicked
f.style.display = 'block';
f.style.visibility = 'visible';
}
Now it's a generic function. Do the same for the "hide" function.
Finally, you can update your validate function to loop over the array of form input fields instead of looking at the one field.
var arrElements = document.getElementsByTagName("input");.
Inside your loop: if( (objElement.type === "radio") && (objElement.checked) ) {.
Don't use if(objElement.id == 'yes'), check for the value of the current field: if(objElement.value == 'yes')
Finally, you can grab the text from the related textarea: objTextArea = document.getElementByName( objElement.name + "_text" );
So, you're just making each of the existing functions generic and looking for the meta data of each field, rather than trying to code for each field.