Dojo Programmatically validate TextBox - javascript

I'm trying to create a dojo form programmatically and validate input TextBox on button click. But when I try to valid I get an error "dijit.byId(..) is undefined. Below is the code:
var form = new dijit.form.Form({
nametb: new dijit.form.TextBox({
name: "name",
type: "text",
required: true,
placeHolder: "Your Full Name"
},"nametb"),
subBtn: new dijit.form.Button({
label: "Proceed",
onClick: function(){
if(dijit.byId("nametb").get('value') == null || dijit.byId("nametb").get('value').length == 0 )
{
alert("Please enter Name");
return false;
}
}
}),
cnclBtn: new dijit.form.Button({
label: "Cancel",
onClick: function(){
dia.hide();
}
}),
postCreate: function(){
this.domNode.appendChild(this.nametb.domNode);
this.domNode.appendChild(this.subBtn.domNode);
this.domNode.appendChild(this.cnclBtn.domNode);
}
});
But now when I click the Proceed button I get an error dijit.byId(...) is undefined
How can I validate this TextBox?

You never set an id for nametb, so dijit.byId() isn't able to find the textbox and throws an error. Try
nametb: new dijit.form.TextBox({
name: "name",
type: "text",
id: "nametb",

Just try with this on specified widget :
// validate nametb textbox
dijit.byId("nametb").validate();
Or you can validate the form like this:
if (dijit.byId("yourForm").validate()) {
// do something if your form is valid
} else {
// show error message
}

Related

SweetAlert input validation

I want the alert to not disappear when the user is trying to submit an empty form,instead it should show some error in the same alert.I tried doing swal.showInputError("some error") but it gives an error that it is not
valid function.I tried looking at the documentation but cannot find any...
Here is my code-
swal({
title:"Enter a Username",
content: {
element: "input",
attributes: {
placeholder: "Type your username",
type: "text"
},
},
className: "mySwal"
}).then((username)=>{
//get the username
if(username){
}else{
}
});
You can use this function:
inputValidator: (value) => {
return !value && 'You need to write something!'
}
This will validates if the user is writing a value.
This will also Work
showCancelButton: true,
preConfirm: (value) => {
if (!value) {
Swal.showValidationMessage(
'You need to write something!'
)
}
}
This works to me
inputValidator: (value) => {
if (!value) return 'Your text here'
else return null
}

Form Validation jQuery plugin success.form.fv event not working

I am trying to build a dynamic popup that allows the user to edit data in a datatable without redirecting the page. I am using NodeJS with jQuery 'modal' library for the popup and 'formvalidation' library to validate and submit the data. (Note: This is not the same library as jquery validate).
Here's a demo of exactly what I am attempting to accomplish.
http://formvalidation.io/examples/loading-saving-data-modal/
I got most of the code working, I was able to display the modal window, passing in data and the validation works properly, too. The problem is that the success.form.fv event is not being triggered, the dialog just closes.
script.
$(document).ready(function () {
$('#editFilepathForm')
.formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
id: {
validators: {
notEmpty: {
message: 'ID is required'
}
}
},
edited_filepath: {
validators: {
notEmpty: {
message: 'Edited Filepath is required'
},
regexp: {
regexp: /^[a-zA-Z\s]+$/,
message: 'The full name can only consist of alphabetical characters'
}
}
},
edited_filename: {
validators: {
notEmpty: {
message: 'Edited Filename is required'
},
regexp: {
regexp: /^[a-zA-Z\s]+$/,
message: 'The full name can only consist of alphabetical characters'
}
}
}
}
})
//THIS EVENT IS NOT TRIGGERING AT ALL. ALERT MESSAGE DOES NOT APPEAR. THE BOX JUST CLOSES AFTER SUCCESSFUL VALIDATION.
.on('success.form.fv', function (e) {
alert('success');
// Save the form data via an Ajax request
e.preventDefault();
var $form = $(e.target),
id = $form.find('[name="id"]').val();
// Hide the dialog
$form.parents('.bootbox').modal('hide');
// You can inform the user that the data is updated successfully
// by highlighting the row or showing a message box
bootbox.alert('The user profile is updated');
//});
});
$('.editButton').on('click', function () {
var id = $(this).attr('data-id');
var requested_filepath = $(this).attr('data-requested-filepath');
var requested_filename = $(this).attr('data-requested-filename');
/*Set original requested values to display in modal form window*/
$('#editFilepathForm')
.find('[name="id"]').html(id).end()
.find('[name="requested_filepath"]').html(requested_filepath).end()
.find('[name="requested_filename"]').html(requested_filename).end()
.find('[name="edited_filepath"]').val(requested_filepath).end()
.find('[name="edited_filename"]').val(requested_filename).end()
// Show the dialog
bootbox
.dialog({
title: 'Edit Requested Filepath',
message: $('#editFilepathForm'),
show: false // We will show it manually later
})
.on('shown.bs.modal', function () {
$('#editFilepathForm')
.show() // Show the login form
.formValidation('resetForm'); // Reset form
})
.on('hide.bs.modal', function (e) {
// Bootbox will remove the modal (including the body which contains the login form)
// after hiding the modal
// Therefor, we need to backup the form
$('#editFilepathForm').hide().appendTo('body');
})
.modal('show');
//});
});
});
I was able to resolve the issue by adding the 'excluded' property as explained in the documentation.
http://formvalidation.io/examples/modal/

How to validate tinyMCE popup textbox value

Please any one help me. I need the tinyMCE popup textbox validation. how to validate the textbox when click on ok Here i use the code below.
tinymce.PluginManager.add('weblink', function(editor, url) {
editor.addButton('weblink', {
text: 'Web Link',
icon: false,
onclick: function() {
editor.windowManager.open({
title: 'Web Link',
body: [
{type: 'textbox', name: 'caption', label: 'Enter Your Caption',maxLength:20},
{type: 'textbox', name: 'weburl', label: 'Enter Your Web URL',maxLength:32}
],
onsubmit: function(e){
var weblinkTxt = "href='"+e.data.weburl+"'";
if(hyperlink!='' && (hyperlink==1 || hyperlink =='1'))
{
editor.insertContent("<a "+weblinkTxt+">"+ e.data.caption+"</a>")
}
else
{
editor.insertContent("<img src='"+emailImg+"'>"+ e.data.caption+" "+e.data.weburl)
}
}
});
}
});
});
I just came across the need to validate the input from a dialog in TinyMCE as well. Unfortunately, it seems there is no native way to do it. However, I found a way to do it, using e.preventDefault().
The idea is to use the e.preventDefault() right after the submit function starts, and manage the dialog window afterwards. This way, it is possible to validate the input:
If it is not valid, then show a warning to the user and do nothing to the dialog window. It will be kept open, and the user will have to insert a new value;
If it is valid, then close the window dialog and continue the method to do whatever you want.
Applied to you example, it would be like this:
tinymce.PluginManager.add('weblink', function(editor, url) {
editor.addButton('weblink', {
text: 'Web Link',
icon: false,
onclick: function() {
editor.windowManager.open({
title: 'Web Link',
body: [
{type: 'textbox', name: 'caption', label: 'Enter Your Caption',maxLength:20},
{type: 'textbox', name: 'weburl', label: 'Enter Your Web URL',maxLength:32}
],
onsubmit: function(e){
//this will prevent TinyMCE from closing the window dialog
e.preventDefault();
/*here you apply your validations to e.data.weburl
and to e.data.caption*/
if(isNotValid){
/*The validation failed, so let's tell the user about it.
The empty function is to let TinyMCE know that it should
do nothing when clicking on the "OK" button. Without it,
I experienced different behaviour when clicking on
"OK" and when pressing "Enter".*/
editor.windowManager.alert('Invalid input!', function(){});
} else {
/*It is valid, so let's first close the
dialog window, and then do what you want*/
editor.windowManager.close();
var weblinkTxt = "href='"+e.data.weburl+"'";
if(hyperlink!='' && (hyperlink==1 || hyperlink =='1'))
{
editor.insertContent("<a "+weblinkTxt+">"+ e.data.caption+"</a>")
}
else
{
editor.insertContent("<img src='"+emailImg+"'>"+ e.data.caption+" "+e.data.weburl)
}
}
}
});
}
});
});
Hope this can still help you or anyone also facing this problem!

Bootstrap Dialog (nakupanda) getting form values [JSFiddle]

I've trouble getting values out of my form.
I'm using bootstrap dialog from nakupanda (http://nakupanda.github.io/bootstrap3-dialog/)
The dialog (it is in a fullcalendar select function)
http://arshaw.com/fullcalendar/docs/selection/select_callback/
var form = $('#createEventForm').html();
BootstrapDialog.show({
message: form,
buttons: [{
label: 'Enkel rooster event',
action: function(dialogItself){
console.log('enkel - create')
dialogItself.close();
}
},{
label: 'Herhalend rooster event (elke dag)',
action: function(dialogItself){
console.log('meer - create')
dialogItself.close();
}
},{
label: 'Close',
action: function(dialogItself){
console.log(dialogItself);
alert('The content of the dialog is: ' + dialogItself.getModal().html());
}
}]
});
The html form
<form id="createEventForm">
<label>Klantnaam</label>
<input type="text" id="titleDrop" />
<br/>
<label>Beschrijving</label>
<input type="text" id="descriptionDrop" />
</form>
I don't know how to retrieve the data from the forms input when someone clicks on a button. I've tried $(titleDrop).val()andgetElementById(titleDrop)
Sometimes the form can contain php.
I am not getting javascript errors. I just don't get anything back when clicking on the butotns and using $('titleDrop').val()
EDIT FIDDLE
http://jsfiddle.net/jochem4207/7DcHW/3
This code works:
var form = '<label>Klantnaam</label><input type="text" id="titleDrop"><br><label>Beschrijving</label><input type="text" id="descriptionDrop">';
BootstrapDialog.show({
message: form,
buttons: [{
id: 'submit1',
label: 'See what you got',
cssClass: 'btn-primary',
action: function(dialogRef){
var titleDropVal = $('#titleDrop').val();
console.log(titleDropVal);
}
}]
});
Still curious if it could work when I dont add the html in the JS section.
Edit: Question 2
I have a select list that gets filled from php
var select = $('<select id="selectVisibleUser"></select>');
<?php
$userList = array();
foreach($this->users as $user){
$jsUser = array(
'key' => $user->webuserId,
'value'=> $user->firstName.$user->preposition.$user->lastName
);
array_push($userList, $jsUser);
}
$list = Zend_Json::encode($userList);
?>
$.each(<?php echo $list?>, function(key, value) {
select.append($("<option/>", {
value: key,
text: value
}));
});
BootstrapDialog.show({
message: function (dialogItself){
var form = $('<form></form>');
dialogItself.setData('select-visible', select);
form.append('<label>Select</label>').append(select);
return form;
},
buttons: [{
id: 'submit1',
label: 'See what you got',
cssClass: 'btn-primary',
action: function(dialogItself){
alert(dialogItself.getData('select-visible').val());
}
}]
});
This shows me a empty select list and returns offcourse a null when I click the button.
Should I use your first fiddle in this case?
Tried the first fiddle ( http://jsfiddle.net/b8AJJ/1/ ) works perfectly in this case (except i've some trouble to get the id instead of the value)
Try this:
http://jsfiddle.net/b8AJJ/
If possible I would suggest this way:
http://jsfiddle.net/7DcHW/4/
BootstrapDialog.show({
message: function (dialogItself) {
var $form = $('<form></form>');
var $titleDrop = $('<input type="text" />');
dialogItself.setData('field-title-drop', $titleDrop); // Put it in dialog data's container then you can get it easier by using dialog.getData() later.
$form.append('<label>Title Drop</label>').append($titleDrop);
return $form;
},
buttons: [{
label: 'Get title drop value.',
action: function (dialogItself) {
alert(dialogItself.getData('field-title-drop').val());
}
}]
});
You're using element selector wrong.
Try $('#titleDrop').val() instead of $(titleDrop).val().
Bind submit event to your form. This way you can get the values of form inputs when the form is submitted. Look at the following example:
http://jsbin.com/xiruv/1/

JQUERY modal box confirm form submit

I have a form that when the submit is hit i want a modal box to pop up with a YES and NO button i want the both the yes and no button to submit the form but i need to know which button they clicked.
Here is my code
<input onclick="$.msgbox('confirm text',{
buttons : [
{type: 'submit', value:'YES'},
{type: 'submit', value:'NO'}
]
}, function(buttonPressed) {
});" name="btnApply" id="btnApply" tabindex="41" src="images/btnsubmit.jpg" style="border-width: 0px;" type="image" />
My problem is the form is submitting when the user clicks submit.
Any help or ideas would be great
thanks
While I'm not familiar with the $.msgbox plugin but you should be opening the modal dialog on <form> submit and not on a button press, as the form can also be submitted by an enter/return on certain input fields (like text boxes <input type="text|password">)
var confirmed = false;
$('#myform').bind('submit', function() {
if (confirmed) {
return true; // confirmation received, continue form submission process
} else {
$.msgbox(
'my modal message',
{
buttons : [
{ type: 'button', value: 'YES' },
{ type: 'button', value: 'NO' }
]
},
function(buttonPressed) {
confirmed = buttonPressed.value; // Update the confirmed variable
$('#myform').submit(); // re-submit the form
}
);
return false; // cancel form submission
}
});
Add return false:
<input onclick="$.msgbox('Would you like a cash advance of up to £1000 whilst we process your loan?',{
buttons : [
{type: 'submit', value:'YES'},
{type: 'submit', value:'NO'}
]
}, function(buttonPressed) {
}); return false;" name="btnApply" id="btnApply" tabindex="41" src="images/btnsubmit.jpg" style="border-width: 0px;" type="image" />
Not sure about the msgbox either but some remarks about your code:
Don't attach your JS logic directly to your code, but use jQuery to attach click event to your markup (see unobtrusive javascript):
Instead of
<input onclick="$.msgbox('confirm text',{
Use
$('#btnApply').click(function(e) {
You can stop the click handling by setting as false one property of the event parameter:
$('#btnApply').click(function(e) {
e.preventDefault(); // stop click handling and so form submitting
Finally, handle the form submitting or not in the msgbox callback function:
$.msgbox("Are you sure that you want to permanently delete the selected element?", {
type: "confirm",
buttons: [
{
type: "submit",
value: "Yes"},
{
type: "submit",
value: "No"},
{
type: "cancel",
value: "Cancel"}
]
}, function(result) {
if(result == "Yes") // display the form on submit
$('form').submit();
});
jsFiddle available.

Categories