Troubleshooting Conditional Form - javascript

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();

Related

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

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/

Sharepoint 2013 People Picker Change event in Javascript

I want People picker Change Event in Javascript as i have to do some task if user is selected/changed in people picker using ClassName.
i have tried the following
$(".Assignedname").bind('input propertychange', function() {
alert("Onchange event" );
})
this fires when i type anything (i.e. text is changed ) , but not fires when user is selected in peoples picker.
Kindly give me some solution. thanks
Once the people picker is initialized, you can access it in the js dictionary and assign a function to the OnValueChangedClientScript property of the picker. The function accepts two parameters, where the second parameter (userInfo) is a collection of users in the picker
var picker = SPClientPeoplePicker.SPClientPeoplePickerDict[pickerId + "_TopSpan"];
picker.OnValueChangedClientScript = function (elementId, userInfo) {
for (var x = 0; x < userInfo.length; x++) {
console.log(userInfo[x].Key);
}
alert("Total number of " + userInfo.length + " users is selected")
};
You need to get the picker id for SharePoint Client People Picker change event. I have got the same using OnUserResolvedClientScript as below. Here to get the picker div I have followed the approach of getting it via the people picker text box id and the title name which you can get the by inspecting the element. put the below code in $(document).ready function. Happy Coding
SP.SOD.executeFunc('clientpeoplepicker.js', 'SPClientPeoplePicker', function() {
var pickerDiv = $("[id^='Employee_x0020_Name'][title='Employee Name']");
var picker = SPClientPeoplePicker.SPClientPeoplePickerDict[pickerDiv[0].id];
picker.OnUserResolvedClientScript = function(peoplePickerId, selectedUsersInfo) {
//It will get the desired display name of the people from picker div, similarly any other property can be accessed via selectedUsersInfo
var empname = selectedUsersInfo[0].DisplayText;
console.log(empname);
}
});
I used jQuery and a focusout event on the input field, instead, to achieve the same effect:
$('input[title="Title of my field"]').focusout(function() {
alert("Focusout event fired." );
doPeoplePickerStuff(); // function for doing validation
});
This has the advantage of being able to check the value of that field whenever they click on anything else - with the exception of the Submit button, if they click that immediately after typing in the field. Here's how I deal with that:
Create a new Submit button and hide the other one:
$('input[name*="diidIOSaveItem"]').parent().append('<input type="button" id="btnSubmit" onclick="doValidation()"></input>'); $('input[name*="diidIOSaveItem"]').hide();
Create the doValidation() function for your new Submit button:
function doValidation() {
doPeoplePickerStuff(); // do validation on the field here
if (personFound == true) {
$('input[name*="diidIOSaveItem"]').click(); // clicks the real button so it does what it normally would
}
}
If you're firing the event in order to grab its value and do validation on it, use:
var personFound = false;
function doPeoplePickerStuff() {
var personFieldSpan = $('span[id*="OriginalTitleOfMyField"]');
var personFieldValue = stripExtraTextFromPeoplePicker(personFieldSpan.text());
if (personFieldValue != "") { // you could do comparisons against the existing value, too, by getting the original value(s) via REST call
personFound = true;
}
}
function stripExtraTextFromPeoplePicker(person) {
var newPerson = person;
console.log("Span text: " + newPerson);
newPerson = newPerson.replace('Title of my field','');
newPerson = newPerson.replace('Enter a name or email address...','');
newPerson = newPerson.replace('Enter names or email addresses...','');
newPerson = newPerson.replace('xSuggestions are available. Use up and down arrows to select.','');
newPerson = newPerson.replace('Suggestions are available. Use up and down arrows to select.','');
newPerson = newPerson.replace('\r','');
newPerson = newPerson.replace('\n','');
newPerson = newPerson.replace('\t','');
newPerson = newPerson.trim();
return newPerson;
}

Validate multiple selectors on click and unclick

jQuery(function($){
var nickname = $('#nickname');
var email = $('#email');
var email_match = $('#email_match');
var password = $('#password');
var birthday_day = $('#birthday_day');
var birthday_month = $('#birthday_month');
var birthday_year = $('#birthday_year');
var gender_femal = $('#gender_female');
var gender_femal = $('#gender_male');
var error = $('.error');
nickname.blur( function(){
if (nickname.val() < 1) error.html('error')
});
nickname.click( function(){
if (nickname.val() > 0) error.html('')
});
});
Now this only works for nickname selector what is the easiest way to check all selectors without copy paste the same function.
for example
blur/focus(function(){if (nickname || email || password < 0) error.html('error'); });
while i'm typing this question i'm getting the idea that the best way is to duplicate the function this because i want to show error if the value is empty.
But i like to hear from the pro's i believe there will be a good way to do this.
You can target them all in one selector, like so:
var fields = $('#nickname, #email, #password, ...');
But it might be easier if you can identify them with something common like:
var fields = $('#some-container :input');
...or:
var fields = $('.form-fields');
Once you have by some means identified a set of all the elements of interest, you may bind the event handlers to all of them at once:
fields.blur(function() {
// 'this' will refer to the DOM node blurred, even though fields refers to all of them
var field = $(this);
if(field.val().length == 0)
error.html('error');
});

CKEditor get table dialog class init Value in Set Up function of another element added on dialogDefinition

PLEASE READ QUESTION BEFORE READING CODE!!!
I've added a checkbox element on Dialog definition of the table dialog (it works). Now I want the checkbox to be checked by default when the table being edited has a certain class (which is usually visible on the advanced tab). According to the documentation, I should be able to do something like this in my setup function. I've tried many things and you could hopefully help me. This is my code.
CKEDITOR.on( 'dialogDefinition', function( evt )
{
var dialog = evt.data;
if(dialog.name == 'table' || dialog.name=='tableProperties')
{
// Get dialog definition.
var def = evt.data.definition;
var infoTab = def.getContents( 'info' );
infoTab.add(
{
type: 'checkbox',
id: 'myCheckBox',
label: 'Table Has Property',
setup: function()
{
//Class to look for if I successfully get the input's value
var classValueToLookFor = 'has-property';
// The current CKEditor Dialog Instance
var thisDialog = CKEDITOR.dialog.getCurrent();
// The Element whose value I want to get
var classElement = theDialog.getContentElement('advanced','advCSSClasses');
// Trying to Get Value of this class Element According to documentation
var containedClasses = theDialog.getValueOf('advanced','advCSSClasses');
// Trying to debug the value above
console.log(containedClasses); // This shows nothing
// Trying to debug InitValue which shows something according to prototype
console.log(classElement.getInitValue()); //This also shows nothing
//Checking if Element has the class I'm looking for to mark the checkbox
if(containedClasses.indexOf(classValueToLookFor) != -1)
{
//Check current checkbox since value has been found
this.setValue('checked');
}
}
onClick: function() // You can ignore this function, just put it in case you were wondering how I'm putting the has-property, might help someone else (works well) ;)
{
var checked = this.getValue();
var classValueToSet = 'has-property';
var thisDialog = CKEDITOR.dialog.getCurrent();
var containedClasses = theDialog.getValueOf('advanced','advCSSClasses');
if(checked)
{
if(containedClasses.indexOf(classValueToSet) != -1)
{
//console.log('already contains class: '+classValueToSet);
}
else
{
containedClasses += containedClasses+" "+classValueToSet;
}
}
else
{
if(containedClasses.indexOf(classValueToSet) != -1)
{
containedClasses = containedClasses.replace(classValueToSet,'');
}
else
{
//console.log('already removed class: '+classValueToSet);
}
}
thisDialog.setValueOf('advanced','advCSSClasses',containedClasses);
}
}
}
Here are some debug statements that can be helpful to add into the setup function and understand what is going on, you shouldn't need to go through all I've went through ;)
console.log('in setup function');
console.log(classElement);
console.log(classElement._);
console.log(classElement.getInitValue());
console.log(classElement.getInputElement());
var inputElement = classElement.getInputElement();
var inputElementId = inputElement.getId();
console.log($('#'+inputElementId+'.cke_dialog_ui_input_text'));
console.log(classElement.getInputElement().value);
It would be nice to test your answer before suggesting. Many of the things I've tried should work in theory, but are practically not working.
Alright, so finally after a few days of trial and error, this is what finally worked for me. Maybe it could be helpful to someone. I'm sure there should be a much cleaner way to do this. All the best to everyone.
setup: function()
{
//This current checkbox
var checkbox = this;
//the class I want to find on my table
var var classValueToLookFor = 'has-property';
//Current Dialog instance
var thisDialog = CKEDITOR.dialog.getCurrent();
//This code below gets a <td> element in the table
var startElement = thisDialog.getParentEditor().getSelection().getStartElement();
// This gets me the parent of the <td> element which is my current table instance
var parentTable = $(startElement.$.offsetParent);
//Finally check if the table has the property I'm looking for.
if(parentTable.hasClass(classValueToLookFor))
{
//Mark the checkbox
checkbox.setValue('checked');
}
}

exchanging values in a select list with jQuery

I'm trying to swap select option values with jQuery when a links clicked, at the moment its just resetting the select when the links clicked, not sure what's going wrong?:
jQuery:
$(function () {
$("#swapCurrency").click(function (e) {
var selectOne = $("#currency-from").html();
var selectTwo = $("#currency-to").html();
$("#currency-from").html(selectTwo);
$("#currency-to").html(selectOne);
return false;
});
});
JS Fiddle here: http://jsfiddle.net/tchh2/
I wrote it in a step-by-step way so it is easier to understand:
$("#swapCurrency").click(function (e) {
//get the DOM elements for the selects, store them into variables
var selectOne = $("#currency-from");
var selectTwo = $("#currency-to");
//get all the direct children of the selects (option or optgroup elements)
//and remove them from the DOM but keep events and data (detach)
//and store them into variables
//after this, both selects will be empty
var childrenOne = selectOne.children().detach();
var childrenTwo = selectTwo.children().detach();
//put the children into their new home
childrenOne.appendTo(selectTwo);
childrenTwo.appendTo(selectOne);
return false;
});
jsFiddle Demo
Your approach works with transforming DOM elements to HTML and back. The problem is you lose important information this way, like which element was selected (it is stored in a DOM property, not an HTML attribute, it just gives the starting point).
children()
detach()
appendTo()
That happens because you remove all elements from both <select> fields and put them as new again. To make it working as expected you'd better move the actual elements as follows:
$("#swapCurrency").click(function(e) {
var options = $("#currency-from > option").detach();
$("#currency-to > option").appendTo("#currency-from");
$("#currency-to").append(options);
return false;
});
DEMO: http://jsfiddle.net/tchh2/2/
You are replacing the whole HTML (every option) within the <select>. As long as each select has the same amount of options and they correspond to each other, you can use the selected index property to swap them:
$("#swapCurrency").click(function (e) {
var selOne = document.getElementById('currency-from'),
selTwo = document.getElementById('currency-to');
var selectOne = selOne.selectedIndex;
var selectTwo = selTwo.selectedIndex;
selOne.selectedIndex = selectTwo;
selTwo.selectedIndex = selectOne;
return false;
});
JSFiddle

Categories