How to do this the with Jquery instead of javascript - javascript

I've been trying to convert this section of script to jQuery instead of vanilla javascript, but I'm not sure how to loop through the elements with jQuery. Basically, I'm grabbing a data attr value from each field to be used as an error message that displays near the field.
This is all inside a click event on the submit button, FYI
What's the jQuery way?
//Set some variables
var invalidFields = $(form).querySelectorAll(':invalid'),
errorMessages = $(form).querySelectorAll('.error-message'),
parent;
// Remove any existing messages
for (var i = 0; i < errorMessages.length; i++) {
errorMessages[i].parentNode.removeChild(errorMessages[i]);
}
//Get custom messages from HTML data attribute for each invalid field
var fields = form.querySelectorAll('.sdForm-input');
for (var i = 0; i < fields.length; i++) {
var message = $(fields[i]).attr('data-ErrorMessage');
$(fields[i]).get(0).setCustomValidity(message);
}
//Display custom messages
for (var i = 0; i < invalidFields.length; i++) {
parent = invalidFields[i].parentNode;
parent.insertAdjacentHTML('beforeend', '<div class='error-message'>' +
invalidFields[i].validationMessage +
"</div>");
}

I converted your code one-to-one to jQuery. But there might be other ways, when i will know where form, setCustomValidity and validationMessage is coming from.
var $form = $(form);
// Remove any existing messages
$(".error-message", $form).remove();
// Get custom messages from HTML data attribute for each invalid field
$(".sdForm-input", $form).each(function() {
var message = $(this).attr('data-ErrorMessage');
// i don't know where the 'setCustomValidity' function is coming from
// this is a custom function
$(this)[0].setCustomValidity(message);
});
// Display custom messages
$(":invalid", $form).each(function() {
// i don't know where 'validationMessage' is comig from
// this is a custom property
$(this).parent().append("<div class='error-message'>" + $(this)[0].validationMessage + "</div>");
});

You can simple replace this.
var fields = form.querySelectorAll('.sdForm-input');
for (var i = 0; i < fields.length; i++) {
var message = $(fields[i]).attr('data-ErrorMessage');
$(fields[i]).get(0).setCustomValidity(message);
}
Replace with jQuery way
var fields = form.find('.sdForm-input');
$.each(fields, function(index, el){
var message = $(el).attr('data-ErrorMessage');
$(el).setCustomValidity(message);
});

Related

Ruby on Rails : Manage array from client side in Rails application?

I am developing a Rails 4 web application. In my Rails application View i have 2 forms . First form contains List of Employees where i can select employees and add to Second Form by clicking on ADD button . Second form also contains a button where i can remove employees from Second Form, all the removed employees will be moved back to first form.
Currently i achieving it like , when i click the add button in First form i will pass the selected employee data to controller through an Ajax call and return the same selected data to second form to display selected employees.
Is it possible to manage this from client side without making any call to Server.
Is there any gems available in Rails to achieve this.
I am using Rails 4 and Ruby 2.
Example : Sample List Manipulation in Javascript
Any help is appreciated.
Yes it's possible to do this on the client-side
Javascript
All I would do is replace your ajax calls with the on-page JS
Have used JQuery in this example (hope that's okay):
http://jsfiddle.net/U443j/3/
$(".move").on("click", "input", function() {
var button = $(this).attr("id");
var from = document.getElementById("FromLB");
var to = document.getElementById("ToLB");
if (button == "left") {
move(to, from);
}else{
move(from, to);
}
});
function move(tbFrom, tbTo)
{
var arrFrom = new Array(); var arrTo = new Array();
var arrLU = new Array();
var i;
for (i = 0; i < tbTo.options.length; i++)
{
arrLU[tbTo.options[i].text] = tbTo.options[i].value;
arrTo[i] = tbTo.options[i].text;
}
var fLength = 0;
var tLength = arrTo.length;
for(i = 0; i < tbFrom.options.length; i++)
{
arrLU[tbFrom.options[i].text] = tbFrom.options[i].value;
if (tbFrom.options[i].selected && tbFrom.options[i].value != "")
{
arrTo[tLength] = tbFrom.options[i].text;
tLength++;
}
else
{
arrFrom[fLength] = tbFrom.options[i].text;
fLength++;
}
}
tbFrom.length = 0;
tbTo.length = 0;
var ii;
for(ii = 0; ii < arrFrom.length; ii++)
{
var no = new Option();
no.value = arrLU[arrFrom[ii]];
no.text = arrFrom[ii];
tbFrom[ii] = no;
}
for(ii = 0; ii < arrTo.length; ii++)
{
var no = new Option();
no.value = arrLU[arrTo[ii]];
no.text = arrTo[ii];
tbTo[ii] = no;
}
}
This will allow you to move the items between form elements. The reason this is important is because it allows you to send the data to the controller as one data-set:
Controller
On my JSFiddle, I have a save button
This can be tied to your Rails controller, allowing you to send your form data to your system
This will send your params hash like this:
params { "FromLB": ["value1", "value2"], "ToLB": ["value1", "value2"] }
The hash will be structured differently, but you'll get two sets of data, which you can then put into your db:
#app/controllers/your_controller.rb
def action
#from = params[:FromLB]
#to = params[:ToLB]
#Save the data-sets here
end

how can I send data from another page by post to bulk domain search page in whmcs?

I have created a page containing a text-area field and few check boxes, from where user can write many domain names in each line in text-area field, and then can choose different domain type through check-boxes. then user clicks on submit button which is redirected to bulk domain search page ?
Link to page where I'm trying to do this is --
http://www.ailogica.com/wp/packages/
I tried to create a simple submit button, but that does not work, then I wrote following code to submit the data by calling a function --
<script type="text/javascript">
function alerttlds() {
jQuery.noConflict();
var i = 0;
var j = 0;
var values = new Array();
var tld = new Array();
var bulkdomains = new Array;
jQuery.each(jQuery("input[name='tld[]']:checked"), function() {
tld[j++] = jQuery(this).val();
});
for(var k = 0; k < tld.length; k++) {
var lines = jQuery('textarea[name=sld]').val().split('\n');
jQuery.each(lines, function(){
bulkdomains[i++] = this+tld[k];
});
}
//alert(bulkdomains.join("\n"));
document.getElementById('bulkdomains').value = bulkdomains.join("\n");
document.forms["bulkchecks"].submit();
}
</script>

how to get username via checked checkbox with javascript or jquery?

i
HTML
<div id="notApprovedUsers">
</div><button onclick="approveUsers()">Approve</button>
</div>
i like to get checked users in parameter userList to work with.
here is javascript there me generating list with users and checkboxes.
i like to approve just the checked one's of course!
JavaScript
function getNotAssignedUsers() {
server.getUsersByGroup("1eb33e30-c355-467f-af3c-e7d0b4a1fgt5").then(function (userDetails) {
debugger;
for (var i = 0; i < userDetails.length; i++)
{
var vorname = userDetails[i].firstName;
var nachname = userDetails[i].lastName;
var newCheckBox = document.createElement('input');
newCheckBox.type = 'checkbox';
newCheckBox.id = "0"+i;
document.getElementById("notApprovedUsers").appendChild(newCheckBox);
var newElement = document.createElement('div');
newElement.id = i;
newElement.className = "notApprovedUsers";
newElement.innerHTML = vorname + " " + nachname;
document.getElementById("notApprovedUsers").appendChild(newElement);
}
});
}
HERE in userList I need to read just a checked users..
function approveUsers(userList)
{
var user1 = document.getElementById("00").checked;
var user2 = document.getElementById("01").checked;
var user3 = document.getElementById("02").checked;
alert(user1 || user2 || user3);
}
You want something like this then. There may be errors as I havent tested
var names = [];
$('input[type=checkbox]:checked').each(function(index, value){
var name = $(value).next("div").html();
names.push(name);
});
Then do something with the names array
Edit - See jsfiddle http://jsfiddle.net/vpg3r/3/
I think the best solution for you here is to use jQuery. You can use something like:
$('#notApprovedUsers input[type=checkbox]:checked')
to get all the elements that are checked, and work with them.
I've created a JSFiddle for you to demonstrate how to implement the behavior that I'm describing. You can see it in this link.

Having a difficulty adding a new form in each new <div>

In my adventure to create a To-Do list application, I've run into another problem. In my code, every time a user clicks New Category a new div will appear with their custom name and number of forms.
However, when another div is created, its' forms are given to the previous div. Here's that code:
<script src="http://code.jquery.com/jquery-2.0.0.js"></script>
<script type='text/javascript' src="script.js"></script>
<script>
$(function() {
$("#new").click(function() {
var canContinue = true;
var newCategory = prompt("Enter the name you want for your category:");
if(newCategory.length === 0){
confirm("A new category can not be created - nothing was entered in the text area.");
canContinue = false;
}
if(canContinue){
var categorySections = prompt("Enter the number of sections needed for this category:");
$("body").append("<div id = \"newDiv\"><p>" + newCategory + "</p></div>");
}
for(var i = 0; i < categorySections; i++){
$("#newDiv").append("<form> Thing to do: <input type = \"text\"></form><br>");
}
});
});
</script>
So, I tried creating a separate function using the this keyword where the forms were created after the div was ready, but now no forms are created at all!
Here's that code:
$(function(){
$("#newDiv").ready(function() {
for(var i = 0; i < categorySections; i++){
$(this).append("<form> Thing to do: <input type = \"text\"></form><br>");
}
});
});
So, how do I create forms for each separate div?
You're repeatedly creating divs with the same ID. (a) that's not legal and (b) if you do it anyway, your $(#newDiv) selector will always apply to the first one.
Also, you're appending to #newDiv outside the if (canContinue) check.
Try:
if(canContinue){
var categorySections = prompt("Enter the number of sections needed for this category:");
var newDiv = $("<div>").appendTo($(document.body));
var header = $('<p>').text(newCategory).appendTo(newDiv);
for(var i = 0; i < categorySections; i++){
newDiv.append("<form> Thing to do: <input type = \"text\"></form><br>");
}
}
jsFiddle
You can't use the ID newDiv multiple times, HTML IDs must be unique. Additionally, your flow can be cleaned up a bit, as below.
$(function () {
$("#new").click(function () {
var newCategory = prompt("Enter the name you want for your category:");
if (newCategory.length === 0) {
confirm("A new category can not be created - nothing was entered in the text area.");
return false;
}
var categorySections = prompt("Enter the number of sections needed for this category:");
var $div = $("<div />", {
html: "<p>" + newCategory + "</p>"
});
$("body").append($div);
for (var i = 0; i < categorySections; i++) {
$div.append("<form> Thing to do: <input type='text'/></form><br>");
}
});
});

Javascript custom validation

I'm writing a custom javascript validation script whereby i iterate through all input elements in a div named 'toggle' and select each that has a class named 'required' and if the value of the element is an empty string (empty) then i need to create labels containing the error message and place them right next to the textbox.
Here's the code:
function clientErrMsgs() {
var container = document.getElementById("toggle");
var inputArray = container.getElementsByTagName("input");
for (var i = 0; i < inputArray.length; i++) {
alert("");
if (inputArray[i].getAttribute("class") == "required" && inputArray[i].value == "") {
var errmsg = inputArray[i].getAttribute("data-errormessage");
var labelErr = document.CreateElement('label');
labelErr.id = "ErrMsg" + i;
labelErr.value = errmsg;
var parent = inputArray[i].parentNode;
parent.appendChild(labelErr);
}
}
}
the program executes well (tested it with alert()) up until the following line:
var labelErr = document.CreateElement('label');
Where is the problem?
you can use asp.net custom validator to do this
i am giving you an example, how to do this....
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Sms length is exceeding over 160."
ClientValidationFunction="validateLength" ControlToValidate="txtSmsMessage"
SetFocusOnError="True" ValidationGroup="add">*</asp:CustomValidator>
<script language="javascript" type="text/javascript">
function validateLength(oSrc, args)
{
args.IsValid = (args.Value.length < 160);
}
</script>
i suggest please try this...
I got things working with:
http://jsfiddle.net/ahallicks/kxPeN/2/
labels don't have a value attribute
Its document.createElement not document.CreateElement
MDC link : document.createElement
Update: you should access the innerHTML of the label and not the value
The snippet
var labelErr = document.createElement('label');
labelErr.id = "ErrMsg" + i;
labelErr.innerHTML= errmsg;
var parent = inputArray[i].parentNode;
parent.appendChild(labelErr);
This is not a direct answer to your question, but would your superior go for a different pre-built validation method? I'm partial to FlowPlayers jQuery based validator. Very simple to setup:
$("#myform").validator();
I've written several validation frameworks in the past. I finally got tired of reinventing the wheel.
May I suggest this:
function clientErrMsgs() {
var container = document.getElementById("toggle");
var inputArray = container.getElementsByTagName("input");
for (var inp, i=0, n=inputArray.length; i<n; i++) {
inp = inputArray[i];
if (inp.getAttribute("class") === "required") {
var errMsg = container.getElementById("ErrMsg"+i);
if (!errMsg) {
errMsg = document.createElement('span');
errMsg.id = "ErrMsg" + i;
errMsg.innerHTML= inp.getAttribute("data-errormessage");
inp.parentNode.appendChild(errMsg);
}
errMsg.style.display= (inp.value === "")?"":"none"
}
}
}

Categories