Javascript - Submit Text Field, Show Div, Hide All Others - javascript

I have a simple form (text field and submit button). I am trying to have the user submit a number, and the resulting number will display one div (from a set of divs).
I tried using this example as a base (when the user clicks a link, it shows a div, but hides others).
My test is below:
var divState = {};
function showhide(oFrm) {
var dividnum = oFrm.Inputed.value;
var prepar = "para";
var divid = prepar + theInput; /* should result in something like "para52" */
divState[divid] = (divState[divid]) ? false : true;
//close others
for (var div in divState){
if (divState[div] && div != divid){
document.getElementById(div).style.display = 'none';
divState[div] = false;
}
}
divid.style.display = (divid.style.display == 'block' ? 'none' : 'block');
}
http://jsfiddle.net/LfzYc/431/
Note: I am NOT proficient in JavaScript at all, which is why I am having difficulty.
Also, I'd like to add a function ... if the number entered is not between 1-4, show a different div, maybe with the id paraEnd.

Please look at the jsFiddle based on your one. I hope I've done what you want. I changed the showhide function and your HTML (fixed div's IDs and added one more div#paraEnd). I'd suggest you refactoring your code.

You should use jQuery to have an easy way to manipulate the DOM.
Using jQuery I made an example for you, just change your JS and paste mine:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
(function ($) {
// get the paragraphs
var paragraphs = $('.paragraph');
// form submit
$('#paragraphform').submit(function (e) {
// prevent the event to flow
e.preventDefault();
// get the input value
var value = $('#Inputed').val() - 1;
// reset all divs removing active css class
paragraphs.removeClass('active');
$('.error').removeClass('active');
// verify if the value doens't exist
if(value < 0 || value > paragraphs.length - 1) {
$('.error').addClass('active');
return;
}
// show the active div
paragraphs.eq(value).addClass('active');
});
})(jQuery);
</script>
Is that what you need?
If you not familiar with jQuery, this is the jquery Learn Center:
https://learn.jquery.com/
And this is a nice tutorial for beginners:
http://www.tutorialspoint.com/jquery/

Related

Troubleshooting Conditional Form

I'm new to Javascript and trying to build a conditional form using bootstrap and JQuery. I would really appreciate the help as I've been working most of the day on this to no avail.
I'm trying to show the div with id physician (and subsequent field) when the select field with the name AppointmentType has a value of Orthopedic or Rheumatology. Here is the link to the live form.
Here is my javascript:
$( document ).ready(function() { //wait until body loads
//Inputs that determine what fields to show
var appttype = $('#secureform input:select[name=AppointmentType]');
var physician = document.getElementById("physician");
appttype.change(function(){ //when the Appointment Type changes
var value=this.value;
physician.addClass('hidden'); //hide everything and reveal as needed
if (value === 'Orthopedic' || value === 'Rheumatology'){
physician.removeClass('hidden'); //show doctors
}
else {}
});
});
These lines are going to cause errors (which you should see in your devtools console):
var appttype = $('#secureform input:select[name=AppointmentType]'); // `input:select` is not a valid selector and causes the rest of the script to fail
physician.addClass('hidden'); // `addClass` is a jQuery method, so this should be `$(physician).addClass('hidden')`
physician.removeClass('hidden');// `removeClass` is a jQuery method, so this should be `$(physician).removeClass('hidden')`
Correct those lines and it should work.
If it helps, I would write it like this:
$( document ).ready(function () {
//Inputs that determine what fields to show
var apptType = $('#secureform select[name="AppointmentType"]'); // dropped the `input:` part
var physician = document.getElementById('physician');
physician.classList.add('hidden'); //hide this initially, outside the change handler
apptType.change(function () { // when the Appointment Type changes
var value = $(this).val().toLowerCase(); // leave case-sensitivity out of it.
var showables = [ // using an array as I prefer using a simple `indexOf` for multiple comparisons
'orthopedic',
'rheumatology',
];
var isShowable = showables.indexOf(value) > -1;
physician.classList.toggle('hidden', !isShowable);
// or, the jQuery equivalent:
// $(physician).toggleClass('hidden', !isShowable);
});
});
Your selector is incorrect:
var appttype = $('#secureform input:select[name=AppointmentType]');
// this should be
var appttype = $('#secureform select[name=AppointmentType]');
Furthermore you are mixing jquery with vanilla JS. Your are using vanilla js here
var physician = document.getElementById("physician");
Physician is now a dom object and not a jquery object. You should use this instead:
var physician = $("#physician");
Additionally you should replace
var value=this.value;
with this
var value= $(this).val();

Javascript search using show() and hide() and adding additional classes

I am using javascript to search through a group of divs while I type. It displays the divs if their title matches what is being typed in the search box and hides any that don't match.
I want to also make the displayed divs have a position of 'initial' instead of 'absolute' so that they move to the top of the page if they are being shown.
I have tried the code below (the line: $('.cbp-item').position='initial';) but it doesn't add the attribute.
I don't seem to get any js errors in the console either.
$( document ).ready(function() {
$('#societies_search').on('keyup',function(){
var valThis = $(this).val().toLowerCase();
if(valThis == ""){
$('.cbp-item').show();
$('.cbp-item').position='initial';
}
else {
$('.cbp-item').each(function(i,item){
var text = $(item).text().toLowerCase();
console.log($(item).find('a').text());
if(text.indexOf(valThis) >= 0) {
$(item).show();
$(item).position='initial';
}
else{
$(item).hide();
}
});
}
});
});
You can use .css() for this
$(item).css('position','initial');

How do i clear text out of a div using javascript

Okay here is what i have:
<script type="text/javascript">
var where = document.getElementById("info")
var texts = false;
function clear() {
where.innerHTML = "";
};
function dostuff(what) {
if(where.style.value === ""){
var comm = document.createTextNode(what);
where.appendChild(comm);
}else {
clear();
}
};
</script>
the id "info" is a div
this is basically a vertical navigation bar that shows tooltips in a div under the buttons when you hover over them.
So I want to first check if the div has no value then if it doesn't then it will append text into it, else it will clear the text but i also want it to append the text after it clears. I'm not sure how to do this and help would be appreciated. thanks
Since you want to clear the item anyways and put your new text in, why even bothering with the conditional? You could just as easily do:
function dostuff(what) {
where.innerHTML = what;
};
Working example

jquery loaded, but not executing proper UI function

I have a validation script, and I'm tying to check if the first name field is left blank. I originally just changed the background color of the field and that worked, but now I want to use jquery to fade in a highlight. This is the code so far.
var x = document.forms['getinfo']['fname'].value;
var validated = true;
if (x==null || x =="") {
//document.getElementById('trfname').style.background="#FF9999";
document.getElementById('trfname').style.borderRadius = '7px';
$("trfname").effect("highlight", {}, 3000);
validated = false;
}
As you can see I commented out the old javascript code that worked and I'm trying to use the jquery highlight function. It's not working and I was wondering if anyone had some input. I've checked if Jquery loads properly and it does, so it's not that. I also included the jquery-ui library, to no avail.
You are looking for an element named trfname, not an id. Add the missing #.
$("#trfname").effect("highlight", {}, 3000);
var x = $('form[name="getinfo"] input[name="fname"]').val();
var validated = true;
if (x.length < 1) {
$('#trfname').css('border-radius', '7px').effect("highlight", {}, 3000);
validated = false;
}

onload function revision to check value of a form

I am working on a website and I came across an interesting situation. In this particular website we are using a form that has given fields filled out that can be modified, etc. Part of this form gives the user the option between choosing one language or up to 6 languages. Each of these particular rows of the form are hidden unless the user clicks an add language button. There is also a remove language button. The problem that I am having is that there is an onload function that someone wrote to display the table on the my account page, but it only goes through and omits the sections of the table that are set to display:none; Here is the code for the current onload function:
<script type="text/javascript">
/* call onload with table id(s) */
function TR_set_toggle()
{
/* toggleRow method */
var toggleRow = function()
{
this.style.display = ((this.style.display == '') ? 'none' : '');
return false;
}
for (var oTable, a = 0; a < arguments.length; ++a)
{
oTable = document.getElementById(arguments[a]);
var r = 0, row, rows = oTable.rows;
while (row = rows.item(r++))
row.toggle = toggleRow;
}
}
onload = function()
{
TR_set_toggle('my_table');
}
</script>
It looks a little sloppy to me but maybe that's because I am new to javascript. Anyways, I want to change the function so it loads the table but also goes through each of the items that display none and check to see if they have input or not to display them. I don't understand the syntax of this.style.display = ((this.style.display == '') ? 'none' : ''); 1. How can I add an if statement into this line of code? 2. How can I check to see if a field has input or is set to the default? Any help is appreciated. Thanks.
How can I add an if statement into this line of code?
((this.style.display == '') ? 'none' : '');
is similar to
if( this.style.display == '' ) {
this.style.display == 'none'
}
else {
this.style.display = '';
}
How can I check to see if a field has input or is set to the default?
I dont understand your question. What do you mean with "field"?

Categories