SharePoint 2010 Change Require Field - javascript

I've added the following code to a SharePoint page - code finds the requested select based on title and alerts when "Decision" value is selected.
Looking to remove the alert and replace with code which finds a specific select (title$=test) and changes it to mandatory/required.
How do you so with SP2010?
<script type="text/javascript" src="/Deploy/jquery.min.js"></script>
<script type="text/javascript" src="/Deploy/jquery.SPServices-0.7.1a.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("select[title$='Based on']").change(function() {
var text = $("select[title$='Based on'] :selected").text();
if (text == "Decision") {
alert('you must provide reason for suspending this order');
}
});
});
</script>
Thanks!

If you are wanting to do validation on a form field it looks like your best bet is to hook into the PreSaveAction method as per this article by Giles Hamson. Inside of your change event you could do the following to mark your field as required:
$("select[title$='test']").attr('required','true');
Then, inside of your PreSaveAction method you could check if the dropdown is required and also if it has a value. Using that you could allow the save to continue or you could stop it and display a validation error.
function PreSaveAction()
{
var dropdown = $("select[title$='test']");
if(dropdown.attr('required') == 'true' && dropdown.val() == "")
{
alert("The field 'test' is required'");
return false;
}
return true;
}

Related

_spBodyOnLoadFunctionNames.push does not work when saving sharepoint site

I have created a method to validate input field in a share point site as you may see in the code below.
The issue is that the method should be activated on saved, but it does not.
For now it is activated on document ready and that is not what I want.
Any advice?
</script>
<script type="text/javascript">
$(document).ready(function(){
ValidateFields();
});
function ValidateFields()
{
if ((document.querySelector('input[name$="BooleanField"]').checked ==false)
&& ($("select[title='Employees selected values'] option").length==0))
{
// $("select[title='Employees selected values'] option").length==0).text("<p>
Please check All employees in department OR select employees </p>");
// // checked, so do something
alert ("Please check All employees in department OR select employees")
}
if ((document.querySelector('input[name$="BooleanField"]').checked ==true)
&& ($("select[title='Employees selected values'] option").length==1)) {
alert ("Please check All employees in department OR select employees23")
}
}
_spBodyOnLoadFunctionNames.push("ValidateFields()");
We can use PreSaveAction method to achieve it. The following code for your reference.
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
function PreSaveAction(){
if ((document.querySelector('input[name$="BooleanField"]').checked ==false)&& ($("select[title='Employees selected values'] option").length==0)){
// checked, so do something
alert ("Please check All employees in department OR select employees");
return false;
}
if ((document.querySelector('input[name$="BooleanField"]').checked ==true)&& ($("select[title='Employees selected values'] option").length==1)) {
alert ("Please check All employees in department OR select employees23");
return false;
}
return true;
}
</script>
You'll need to override the "Submit" handler of the form. Depending on the ID of your button, this might work:
$(document).ready(function() {
$("input[id$='SaveItem']").each(function() {
// get the button
var button = $(this);
// reference the existing handler for later use
var existingHandler = this.onclick;
// clear the existing handler
this.onclick = null;
// add your custom handler that validates first, then "submits" if successful
button.click(function() {
if(ValidateFields()){ // change ValidateFields to return true/false
existingHandler(); // validation passed, now call original handler
}
});
});
});

jQuery get / set value of textbox value in a repeater

I have a repeater with textboxes ID="txtBomName" in an ascx page with a value retrieved from datatable on pageload.
the end user can change the value, must be not be null/empty.
I have jquery to check if null/empty on change or blur, produce alert if null then I would like the null value set back to original else set value as user entered.
This does work if, I use the generated control ID i.e:
$("#p_lt_ctl02_pageplaceholder_p_lt_zoneMainContent1_BOM_rptBoms_ctl00_txtBomName)"
this obviously only works for the the first textbox on the page, as the "ct100" part of the ID changes for each box.
code:
$(document).ready(function () {
$("#p_lt_ctl02_pageplaceholder_p_lt_zoneMainContent1_BOM_rptBoms_ctl00_txtBomName").change(function () {
var oldVal = this.getAttribute('value');
if (this.value == null || this.value == "") {
alert("Please ensure the name is not empty");
$("#p_lt_ctl02_pageplaceholder_p_lt_zoneMainContent1_BOM_rptBoms_ctl00_txtBomName").val(oldVal);
}
else {
$("#p_lt_ctl02_pageplaceholder_p_lt_zoneMainContent1_BOM_rptBoms_ctl00_txtBomName").val(this.value);
}
});
});
so, I changed the code to look for id$=txtBomName and set an alert to (this.id) the id for each box shows correctly, how can I set the value of the textboxes using (this.id).val(oldVal); ?
You need to use:
$(this).val(oldVal);
'this' is a reference to the current object i.e. textArea the abouve code will set the value of the textArea
Try this code
$(document).ready(function () {
// The simplest way is to save the original value using data() when the
// element gets focus.
$("input[id$='txtBomName']").on('focusin', function(){
$(this).data('val', $(this).val());
});
$("input[id$='txtBomName']").change(function () {
var txtBox=$(this);
var prev = txtBox.data('val');
var current = txtBox.val();
if (current) {
txtBox.val(current);
}
else {
alert("Please ensure the name is not empty");
txtBox.val(prev);
}
});
});

How to trigger a JavaScript event on a target page AFTER the user navigates to that page from another

How can I trigger an javascript (or jquery) event when I go to other page?
For exemple:
I'm at index.html
At index.html, I clicked on contact.html link;
When I go to contact.html page, I need to trigger an event
Thanks for for your attention
EDIT:
I will try to explain in other way:
I am working with RubyOnRails. I have a page where I can add contacts. There are a lot of fields but for this example I will use only two:
<select name='type' id='type_select'>
<option value='0'></option>
<option value='1'>Home</option>
<option value='2'>Work</option>
</select>
<input type="text" name="contact_name" id="contact_name_input">
On my Javascript I have:
// this only works if I press CTRL+F5 to refreash the page
$(document).ready(function(){
$("#contact_name_input").hide();
});
// This Works fine
$('#type_select').change(function(){
if ($(this).val() == 1 || $(this).val() == 2){
$("#contact_name_input").show();
} else {
$("#contact_name_input").hide();
}
});
In other words, what I need is to hide the input field when the user visit the page and to show it only if he selected a valid type.
I hope to have been more clearer
Thanks for your attention
It seems like you want to have an event triggered on the target page (after the user has clicked on a link) and is taken to the destination page. If that is the case and you want to trigger a specific event, as others have suggested, your first entry point would probably be document.ready of the new page and you can use a querystring to specify a more specific event.
On Index.html
Contact
On Contact.html
<script type="text/javascript">
$(function() {
$(document).bind("myCustomEvent", function(e, data) {
alert("Weee, you triggered event id: " + data.EventId + "!");
});
var eventId = getParameterByName('e'); // Load the query string specified by the previous page's link
if(eventId == 1) {
$(document).trigger("myCustomEvent", {EventId: eventId});
} else {
} // end if/else
});
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
</script>
Credit -- Javascript QueryString function shamelessly taken from here: How can I get query string values in JavaScript?
Posting the solution Given by #xDaevax on chat:
By using the JQuery on $(document).ready(); to hide the input, you will sometimes see a flicker.
You may want to consider adding some CSS to the input to hide it
then, it will always be hidden when you come to the page.
When yo uuse the JQuery show() and hide(), they will change the "display" css attribute from "display: block", to "display: none" depending on whether you call show() or hide()
so, in your javascript, you could try:
$("#type_select").change(function(e) {
var selectedValue = $(this).val();
if(selectedValue <= 0) {
$("#contact_name_input").hide();
} else {
$("#contact_name_input").show();
}
});
It works for me

How to validate a memorized value in an input box

I have the following code:
$(":input").bind("keyup change", function(e) {
var comboVal = $('.emailrequerido1').val()+$('.emailrequerido2').val()+$('.emailrequerido3').val()+$('.emailrequerido4').val()+$('.emailrequerido5').val();
if(comboVal == 'nullnull' || comboVal == ""){
$("#enviarForm").attr('disabled', true);
}else{
$("#enviarForm").removeAttr('disabled');
}
});
What I am trying to accomplish is that when you select a memorized value from the input box by double clicking in the box a history of inputs shows (these values are saved by the browser (I believe)) and if you choose one of these and the field has that text you selected the button should enable.
Here is a JSFiddle example: JSFiddle example
In the example I added a value to the first field since these dont memorize as I expalined before to show a demonstration of what I mean.
I have cleaned up the code a bit: http://jsfiddle.net/kam5B/1/
I've swapped the classes and ids so that the ids are unique, and the classes are common.
Here is a checkEmails function that runs the validation and enables/disables the checkbox.
checkEmails is run every time an input changes, and when the page loads the first time:
$(document).ready(function () {
function checkEmails() {
var nonempty = $('form .email_contactopadrino').filter(function() {
return $(this).val() != '';
});
if (nonempty.length) {
$('#enviarForm').removeAttr('disabled');
}
else {
$('#enviarForm').attr('disabled', true);
}
};
$('form').on('keyup change', '.email_contactopadrino', checkEmails);
checkEmails();
});

Select individual form with Javascript

<script>
$(document).ready(function() {
$('form["meldaan"] input').keyup(function() {
var empty = false;
$('form["meldaan"] input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
});
</script>
This script works fine with one form, but I have two or three different forms on one page. I want each form to be treated different, if I use this code all fields in ALL forms need to be filled in, which I obviously don't want.
How can I identify the unique forms? Say one form is named name="formone" and the other name="formtwo". How would I implement that? (It's okay if I have to make more functions).
You just need to adjust your selector:
$('form[name="formone"] > input')
Update: #Andre, in your live example inputs are not direct children of the form element, so you need to use:
$('form[name="formone"] input')
Update 2: if you are using an id:
$('#formid input')

Categories

Resources