Dear all I am using jQuery Grid to display data for user administration. When I click on '+' sign, I get a Dialog box that pops up, wherein I can create a new user. I use a server-side call to populate cascading lists.
When I submit the request: On failure, or even on success, the 'Loading...' button never seems to disappear. I fear that I am leaving some resource open, or worse. As I am inheriting this application, and have no jQuery experience whatsoever, I was hoping you could help me. I apologize in advance if this is something really simple; but, I could not find anything on the Web that help me resolve this issue.
I am using Struts 2 along with jQuery; however, I don't think we use the jQuery Struts 2 plugin. Thanks in advance.
Here is the code:
<%# include file="/WEB-INF/jsp/fragments/directive.jsp" %>
<s:if test="hasActionErrors()">
<div class="error">
<s:actionerror/>
</div>
</s:if>
<s:form action="userAdminCreateSubmit" namespace="/ti/tmsportal/ga" onsubmit="return false;" >
<s:textfield key="user.username" required="true" />
<s:textfield key="user.firstName" required="true" />
<s:textfield key="user.middleInitial" />
<s:textfield key="user.lastName" required="true" />
<s:textfield key="user.email" required="true" />
<s:textfield key="user.phone" required="true" />
<s:select key="user.organizationId" list="organizations" listKey="value" listValue="label" required="true" onchange="changeWorkgroups(this.value);changeRoles(this.value);" />
<s:select key="user.workgroupId" list="workgroups" listKey="value" listValue="label" onchange="changeLocations(this.value);" />
<s:select key="user.locationId" list="locations" listKey="value" listValue="label" />
<s:select key="user.portalRole" list="roles" listKey="value" listValue="label" emptyOption="true" required="true" onchange="changeLevels(this.value);" />
<s:select key="user.levelCode" list="levels" listKey="value" listValue="label" emptyOption="true" required="true" />
</s:form>
<s:url action="lookup" var="workgroupLookupUrl" >
<s:param name="type">workgroupsInOrganization</s:param>
</s:url>
<s:url action="lookup" var="locationLookupUrl" >
<s:param name="type">locationsInWorkgroup</s:param>
</s:url>
<s:url action="lookup" var="roleLookupUrl" >
<s:param name="type">rolesForOrg</s:param>
</s:url>
<s:url action="lookup" var="levelLookupUrl" >
<s:param name="type">levelsForRole</s:param>
</s:url>
<script>
function changeWorkgroups(key)
{
$('#userAdminCreateSubmit [name="user.workgroupId"]').load('<s:property value="#workgroupLookupUrl" />&key=' + key + ' option',
function(responseText, textStatus, XMLHttpRequest) {
changeLocations();
setVisibility();
}
);
}
function changeLocations(key)
{
$('#userAdminCreateSubmit [name="user.locationId"]').load('<s:property value="#locationLookupUrl" />&key=' + key + ' option',
function(responseText, textStatus, XMLHttpRequest) {
setVisibility();
}
);
}
function changeRoles(key)
{
$('#userAdminCreateSubmit [name="user.portalRole"]').load('<s:property value="#roleLookupUrl" />&key=' + key + ' option',
function(responseText, textStatus, XMLHttpRequest) {
changeLevels($('#userAdminCreateSubmit [name="user.portalRole"]').value());
});
}
function changeLevels(key)
{
$('#userAdminCreateSubmit [name="user.levelCode"]').load('<s:property value="#levelLookupUrl" />&key=' + key + ' option');
}
function setVisibility()
{
$('#userAdminCreateSubmit [name="user.workgroupId"]').parents('tr').toggle(
$('#userAdminCreateSubmit [name="user.workgroupId"] option[value!=""]').size() > 0
);
$('#userAdminCreateSubmit [name="user.locationId"]').parents('tr').toggle(
$('#userAdminCreateSubmit [name="user.locationId"] option[value!=""]').size() > 0
);
}
$(function()
{
$('.button').button();
setVisibility();
addFieldHint('user.receiveNotifications', '<s:text name="content.help.receiveNotifications" />');
addFieldHint('user.username', '<s:text name="content.help.username" />');
});
function submitUserAdminCreate()
{
$.post('<s:url action="userAdminCreateSubmit" namespace="/ti/tmsportal/ga" />', $('#userAdminCreateSubmit').serialize(),
function(data) {
$('#userAdminDialog').empty().append(data);
}
);
}
</script>
To fix your JS error, just change
$('#userAdminCreateSubmit [name="user.portalRole"]').value()
to
$('#userAdminCreateSubmit [name="user.portalRole"]').val()
Related
I have div which needs to be repeated(create dynamically) on a button click.i have a working code,but it needs to be used many places across pages so i would like to make it a generic one,like i need to pass only particular div id as an input parameter to that method.
function textbox_add(id){
console.log(id)
var counter = 0;
$('#'+id).on('click','.newField', function () {
console.log(counter);
if(counter >= 3){
alert("Reached Maximum");
return false
}
var newthing=$('div.addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').end();
$('#'+id).append(newthing);
counter++;
});
$('#'+id).on('click','.remove', function () {
if (counter == 0)
{
return false
}
$(this).parent().remove();
counter--;
});
}
if i use it outside the method it works perfect.The goal is to create 4 text boxes dynamically and if i remove it should remove one by one.
here is my fiddle
Demo
Issues facing when i place inside method are:
On first click it creates single div on second click it creates two div's then continues for further click's.
On clicking remove it works like create.
when i click new again it creates the total of removed,created(earlier) all the div's.
I am not able to find where am missing.
I am not too sure what you are trying to do with the id (I assume it is your div id) that you are adding but you can try replacing your counter with a count of the elements:
function textbox_add(id){
$('#'+id).on('click','.newField', function () {
if($("#" + id + " > .addNew").length >= 4){
alert("Reached Maximum");
return false
}
var newthing=$('div.addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').end();
$('#'+id).append(newthing);
});
$('#'+id).on('click','.remove', function () {
if ($("#" + id + " > .addNew").length == 1)
{
return false
}
$(this).parent().remove();
});
}
textbox_add('test');
working Fiddle
OP basically wants an onclick(html) on the add button, like:
function textbox_add(id) {
if ($("#" + id + " > .addNew").length >= 4) {
alert("Reached Maximum");
return false;
}
var newthing = $('#'+id+' .addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').attr('onclick','').end();
$('#' + id).append(newthing);
$("#" + id + " > .addNew").on('click', '.remove', function () {
if ($("#" + id + " > .addNew").length === 1) {
return false;
}
$(this).parent().remove();
});
}
working codePen
It works fine, fiddle
You need to pass a wrapper id since you're cloning the .addNew content.
Example:
<div class="container" id="test">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
JS
textbox_add('test');
Your code was actually working well when you use id as selector, but worked wrong (adding multiple times new inputs for example) when you were using class as selector (because multiple elements share the same class).
I have edited it so you can use with id and class selectors:
HTML
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" />
<br />
<br />
</div>
</div>
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" />
<br />
<br />
</div>
</div>
<div id="other_container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" />
<br />
<br />
</div>
</div>
JS
function textbox_add(selector){
console.log(selector);
var max_allowed = 3;
$(selector).on('click','.newField', function () {
console.log($(this).parents(selector).find(".addNew").length);
if($(this).parents(selector).find(".addNew").length > max_allowed){
alert("Reached Maximum");
return false
}
var newthing=$('div.addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').end();
console.log($(this).parents(selector));
$(this).parents(selector).append(newthing);
});
$(selector).on('click','.remove', function () {
if (!$(this).parents(selector).find(".addNew").length > 1){
return false
}
$(this).parent().remove();
});
}
textbox_add(".container");
textbox_add("#other_container");
And here is the working JSFiddle.
I think that this is not the correct way to approach the problem, but the OP really wants to do it this way.
HTML
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" onClick="textbox_add(this)" />
<br />
<br />
</div>
</div>
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" onClick="textbox_add(this)"/>
<br />
<br />
</div>
</div>
JS
function textbox_add(element){
var max_allowed = 3;
if($(element).parents(".container").find(".addNew").length > max_allowed){
alert("Reached Maximum");
return false
}
var newthing = $('div.addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').attr('onclick','textbox_remove(this)').unbind('click').end();
$(element).parents(".container").append(newthing);
}
function textbox_remove(element){
if (!$(element).parents(".container").find(".addNew").length > 1){
return false
}
$(element).parent().remove();
}
Working JSFiddle
I think this might be what you are trying to do. The main thing I'm not sure of is what you intend to pass in as the id parameter. But tell me if this fills the bill.
http://jsfiddle.net/abalter/xdsacvdm/12/
html:
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" />
<br />
<br />
</div>
</div>
JavaScript:
$('#createField').on('click', function () {
//alert('new field clicked');
var el = createField('some-id', $('#generator').val());
$('.container').append(el);
});
function createField(id, text) {
var numFields = $('.container').find('.added').length;
if (numFields>3)
{
alert("Maximum reached");
return false;
}
var $outerDiv = $('<div>').addClass('newOne').addClass('added').attr('id', id);
var $textBox = $('<input>').attr({'type': 'text','value': text});
var $button = $('<input>').attr({'type': 'button' , 'value': 'Remove Field!'});
$outerDiv.append($textBox);
$outerDiv.append($button).append('<br/>').append('<br/>');
$button.on('click', function(){
$(this).closest('div').remove();
});
return $outerDiv;
}
SCRIPT:
function dodelete(id,deleted) {
/*alert("UserId");*/
$("input[id$='hdUserId']").val(id);
$("input[id$='hdnDeleted']").val(deleted);
//alert(id);
//alert(deleted);
setParams(id,deleted);
//setInterval(50000);
alert('Record deleted successfully!');
}
PAGE:
</tr>
<apex:repeat value="{!staffInfo.StaffAccepted}" var="u" id="staffaccepted" rendered="{!staffInfo.StaffAccepted.size <> 0 && staffInfo.StaffAccepted.size <> null}">
<tr>
<td>{!u.FullName}</td>
<td>{!u.Email}</td>
<td>{!$Label[u.Role]}</td>
<td>{!$Label[u.RegType]}</td>
<td>
{!$Label.PG_ApprovalProcess_Reset}/
<apex:outputPanel rendered="{!IF(u.valide, true, false)}">
<apex:form style="margin:0px;">
<apex:commandLink onclick="dodelete('{!u.contact}',true);" > Delete</apex:commandLink>
<!--<apex:actionSupport event="onclick" action="{!dodelete}" rerender="tabref"/>-->
</apex:form>
</apex:outputPanel>
</td>
</tr>
</apex:repeat>
<apex:form >
<apex:actionFunction action="{!dodelete}" name="setParams" rerender="dummy">
<apex:param name="param1" assignTo="{!UsId}" value="" />
<apex:param name="param2" assignTo="{!userDeleted}" value="" />
</apex:actionFunction>
</apex:form>
Controller:
public void dodelete()
{
System.debug('PG_ApprovalController.doAction() called: Id: ' + UsId + ' and approved: ' + userDeleted);
/*Contact contact = [select Id, PG_ContactApprovalState__c from Contact where Id = :this.UsId];
PG_ContactApprovalStatus__c cas = [select Id, PG_ApprovalStatus__c from PG_ContactApprovalStatus__c where Id = :contact.PG_ContactApprovalState__c];
system.debug('PG_ContactApprovalStatus__c found, Id : ' + cas.Id + ', status : ' + cas.PG_ApprovalStatus__c);
if(userDeleted)
{
cas.PG_ApprovalStatus__c = PG_Enums.APPROVAL_STATUS_TYPE.Deleted.name();
update cas;
system.debug('Deleted');
} */
Contact contact = [select Id, PG_ContactApprovalState__c from Contact where Id =:this.UsId];
PG_ContactApprovalStatus__c cas = [select Id, PG_ApprovalStatus__c from PG_ContactApprovalStatus__c where Id = :contact.PG_ContactApprovalState__c];
system.debug('PG_ContactApprovalStatus__c found, Id : ' + cas.Id + ', status : ' + cas.PG_ApprovalStatus__c);
if(userDeleted)
{
cas.PG_ApprovalStatus__c = PG_Enums.APPROVAL_STATUS_TYPE.Deleted.name();
update cas;
system.debug('Deleted');
PageReference nextPage = new PageReference('/apex/PG_PharmacyOverview');
nextPage.setRedirect(true);
}
//update cas;
system.debug('Entered ###########>>>>>>>>>>:'+p);
}
I want to refresh the page after deleting the user from table,
Note:-
If i delete the LINE "alert('Record deleted successfully!');" from script page refresh is not working, even the delete function also not working.
You need to refresh the table when the action function is processed, you can do that with rerender attribute.
add rerender attribute to the action function, which the id of the component to be refreshed:
<apex:actionFunction action="{!dodelete}" name="setParams" rerender="contactTablePanel">
<apex:param name="param1" assignTo="{!UsId}" value="" />
<apex:param name="param2" assignTo="{!userDeleted}" value="" />
</apex:actionFunction>
encapsulate the table inside panel and assign a Id or add id to any desired component to be refreshed from apex:actionfunction-
<apex:outputPanel id="contactTablePanel">
<table>
....
</table>
</outputPanel>
I've added the following function to my wordpress theme javascript file wp-content/themes/xxx/js/script.js
function calculateBmi() {
var weight = document.bmiForm.weight.value
var height = document.bmiForm.height.value
if (weight > 0 && height > 0) {
var finalBmi = weight/(height/100*height/100)
document.bmiForm.bmi.value = finalBmi
if (finalBmi < 18.5) {
document.bmiForm.meaning.value = "That you are too thin."
}
if (finalBmi > 18.5 && finalBmi < 25) {
document.bmiForm.meaning.value = "That you are healthy."
}
if (finalBmi > 25) {
document.bmiForm.meaning.value = "That you have overweight."
}
}
else{
alert("Please Fill in everything correctly")
}
}
I have added the following code on a wordpress page (in admin) with a form that calls the function when you press the button
<form name="bmiForm">
Your Weight(kg): <input type="text" name="weight" size="10"><br />
Your Height(cm): <input type="text" name="height" size="10"><br />
<input type="button" value="Calculate BMI" onClick="calculateBmi()"><br />
Your BMI: <input type="text" name="bmi" size="10"><br />
This Means: <input type="text" name="meaning" size="25"><br />
<input type="reset" value="Reset" />
</form>
Nothing happens when I click the button and chrome console gives the following message.
Uncaught ReferenceError: calculateBmi is not defined ?page_id=1368:126
onclick
What is it that is wrong?
It's just a matter of enqueuing properly. First, a test page with the HTML provided. Note the use of the global $b5f_hook to catch our page afterwards.
add_action( 'admin_menu', 'add_auxiliary_menu' );
function add_auxiliary_menu()
{
global $b5f_hook;
$b5f_hook = add_menu_page(
'Test',
'<span style="color:#e57300;">Test</span>',
'edit_pages',
'b5f_page_id',
'b5f_page_callback',
'', // icon default for empty
1 // create before Dashboard menu item
);
}
function b5f_page_callback()
{
?>
<form name="bmiForm">
Your Weight(kg): <input type="text" name="weight" size="10"><br />
Your Height(cm): <input type="text" name="height" size="10"><br />
<input type="button" value="Calculate BMI" onClick="calculateBmi()"><br />
Your BMI: <input type="text" name="bmi" size="10"><br />
This Means: <input type="text" name="meaning" size="25"><br />
<input type="reset" value="Reset" />
</form>
<?php
}
Enqueuing the script, not sure why jQuery is being included as dependency, but it doesn't matter:
add_action( 'admin_enqueue_scripts', 'b5f_enqueue' );
function b5f_enqueue( $hook )
{
global $b5f_hook;
if( $hook !== $b5f_hook ) # Not our page, bail out
return;
$jscriptURL = get_stylesheet_directory_uri() . '/js/script.js';
wp_enqueue_script( 'custom_script', $jscriptURL, array('jquery'), '1.0', true );
}
And the script file contains the JS code provided:
function calculateBmi() { /* rest of the code */ }
your function is not defined because it contains syntax errors.
Add ";" after each line and check for other errors e.g. using jslint tool
I got a basic HTML form which I validate through jQuery,
this is the form:
<form method="post" action="index.php" enctype="multipart/form-data" id="add_product">
מק"ט:
<input type="text" name = "product_cn" value="<?php echo $product_cn;?>" id="cn"/> <span style="margin-right: 20px; color:red; display:none" id="cn_exist"></span>
<br /> <br />
שם המוצר:
<input type="text" name="product_name" value="<?php echo $product_name;?>" id="p_name"/>
<br /> <br />
פרטי המוצר:
<textarea rows = "6" cols = "30" name="product_details" id="p_details"> <?php echo $product_details;?></textarea>
<br /> <br />
מחיר:
<input type="text" name = "product_price" value="<?php echo $product_price;?>" id="p_price"/>
<br /> <br />
תמונה:
<input type="file" name="fileField" id="p_image" />
<br /> <br />
<input type="submit" name="submit" value="רשום מוצר" />
</form>
this is my validation code:
$("form").submit(function(e){
e.preventDefault(e);
var p_cn = $("#cn").val();
var p_name = $("#p_name").val();
var p_details = $("#p_details").val();
var p_price = $("#p_price").val();
var p_image = $("#p_image").val();
error = "";
if(!(p_cn != "") || !(p_cn.length > 0)){
error += " אנא הוסף הוסף מק\"ט <br /> <br />" ;
}
if(!(p_name != "") || !(p_name.length > 0)){
error += "אנא הזן שם מוצר <br /> <br />";
}
if(!(p_price != "") || !(p_name.length > 0)){
error += " אנא הזמן מחיר. <br /> <br />";
}
if(error != ""){
$("#form_errors").html(error).hide().slideDown(500);
}else{
$("#form_errors").slideUp(500);
$("#add_product").submit();
}
});
Please ignore any character you don't understand, it's my language.
As you can see, what I did is prevent the form from being submitted, I had to use the selector "form" or otherwise, it just won't work for some reason >_<. Therefore, I tried using the selector "form" and it worked.
Now, as you can see in the last IF condition, I want to submit the form if the variable "error" is empty, but the form just doesnt submit. I would like to know how to make the form submit :-)
Thanks in advance!
e.preventDefault(e); (which should be just e.preventDefault();) stops the submit from happening. You need to do that conditionally:
if (error) {
e.preventDefault();
} else {
// No need to prevent the submit
}
The purpose of e.preventDefault() is to stop the element's default action. In a form.submit(), it prevents the form from being submitted.
Here is a detailed explanation
Move the preventDefault() to here:
if(error != ""){
$("#form_errors").html(error).hide().slideDown(500);
e.preventDefault(); //do NOT want it to submit if there are errors
}else{
$("#form_errors").slideUp(500);
$("#add_product").submit();
}
I have a form with different input texts, I want to validate my form in client side, so I have written a java script function and the validation of the form is based on a property in the defined bean(userManagement.update), it means that if userManagement.update is true, these input texts are not required, but if userManagement.update is false, these input texts are required.
the problem is userManagement.update does not change in javascript function.
<h:outputLabel for="pwd1" value="* #{i18n['password']}: "
rendered="#{!userManagement.update}" />
<h:outputLabel for="pwd1" value=" #{i18n['password']}: "
rendered="#{userManagement.update}" />
<p:password id="pwd1" value="#{userManagement.user.password}"
match="pwd2" label="Password 1"
required="#{!userManagement.update}"
requiredMessage="#{i18n['password_required']}"
validatorMessage="#{i18n['password_match_repeat_password']}" />
<span style="color: red" id="emptyPasswordError" />
<h:outputLabel for="pwd2" value="* #{i18n['repeat_password']}: "
rendered="#{!userManagement.update}" />
<h:outputLabel for="pwd2" value=" #{i18n['repeat_password']}: "
rendered="#{userManagement.update}" />
<p:password id="pwd2" value="#{userManagement.user.password}"
required="#{!userManagement.update}"
requiredMessage="#{i18n['repeat_password_required']}" />
<span style="color: red" id="emptyRepeatPasswordError" />
<p:commandButton value="#{i18n['update']}"
actionListener="#{userManagement.update}">
</p:commandButton>
<script type="text/javascript">
function validateForm() {
if ($("#addUserform:pwd1").val() === "")
{
if("#{!userManagement.update}"){
$("#emptyPasswordError").text("#{i18n['password_required']}");
validation = false;
}
}
else{
$("#emptyPasswordError").text("");
}
if ($("#addUserform:pwd2").val() === "")
{
alert("#{!userManagement.update}");
if("#{!userManagement.update}"){
$("#emptyRepeatPasswordError").text( "#{i18n['repeat_password_required']}");
validation = false;
}
}
else{
$("#emptyRepeatPasswordError").text("");
}
return validation;
}
</script>