How to validate for empty text input? Required message will show when input textfield is empty.
<script>
function LoadData(data){
var tempdata = data;
var i=0;
while (i<tempdata.activity.length) {
var index = Math.floor(Math.random() * tempdata.activity.length);
qHint[i] = tempdata.activity[i].hint;
i++;
}
}
function hint(data, i){
$('#mypanel' + (i + 1)).append("<label for=text" + (i + 1) + " id=panel"+ (i + 1)+ " style='margin-top:10%;text-align:center;color:white;'><span id=panelTitle"+ (i + 1) +" >"+ data + "</span></label>");// panel item
$('#panel' + (i + 1)).append('<input type="text" name="name" id=text'+ (i + 1) + ' style="text-align: center">');
$('#mypanel' + (i + 1)).append('Submit');
$('#mypanel' + (i + 1)).append('Cancel');
}
function submitFunc(num){
$("#text"+num).attr("disabled", true);
$("#text"+num).attr("readonly", true);
}
</script>
You will want to look into using the jQuery method val() which returns the value of, amongst other things, an input of type textbox.
If you are using it within your submitFunc() method:
function submitFunc(num){
if($('#text' + num).val() != ''){
$("#text"+num).attr("disabled", true);
$("#text"+num).attr("readonly", true);
}
}
You can use jquery.validate.js for this purpose. You'd just need to add required class on the input field.For example:
<input type="text" id="Field1" class="required" />
Then on document.ready, just calling $("#FormName").validate function would validate that form and its fields for you.Must note that the input fields to be validated must be part of a form.
Related
I'm creating a front-end page where user can create textarea by pressing a button and then save the information in the localStorage. When the load button is pressed, the same number textareas appear and their content comes from the localStorage. The problem is that when I retrieve the info from the localStorage, the value has "", which I want to remove.
I have tried replace(/"([^"]+(?="))"/g, '$1');
i = localStorage.getItem('AllNum');
// Allnum is the is where the generated textareas are placed
function add() {
//i represents the number of textareas
i++;
$('#alltxt').append('<div class="textarea"><input></input><textarea id="txt' + i + '"></textarea></div>');
}
function save() {
for (var a = 1; a <= document.getElementById("alltxt").childElementCount; a++) {
localStorage.setItem("txt" + a, document.getElementById('txt' + a).value);
}
localStorage.setItem('AllNum', i);
}
function load() {
if (document.getElementById("alltxt").childElementCount < localStorage.getItem('AllNum')) {
for (var i = 1; i <= localStorage.getItem('AllNum'); i++) {
$('#alltxt').append('<div class="textarea"><input></input><textarea id="txt' + i + '">"' + invert(i) + '"</textarea></div>');
}
}
}
function invert(i) {
var a = localStorage.getItem('txt' + i);
a = a.replace(/"([^"]+(?="))"/g, '$1');
return a;
}
https://codepen.io/abooo/pen/RvbOzV?editors=1010
To test the code generate some textareas, then enter some values in them and press +. After this reload the page. Finally click Load button. You can see that 123 changed into "123"
The problem is that you have "" around the text you are putting in.
In your load function, change "' + invert(i) + '" to ' + invert(i) + ' (Remove the two ").
This question already has answers here:
How to pass data from Javascript to PHP and vice versa? [duplicate]
(7 answers)
Closed 4 years ago.
I have an array named "seat" in my javascript file.It is used to store the seat numbers when a user clicks on a seat in a theater layout.In my function,I've used a window alert to show the user his selected seats,and when he clicks OK button,I want to send these booked seats(values in my array) to a php file named "confirm".
Here is the javascript function.
var init = function (reservedSeat) {
var seat = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
seat.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(seat.join(''));
};
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)){
alert('This seat is already reserved!');
}
else{
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnsubmit').click(function() {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
window.alert(seat);
$_POST('confirm.php', {seat: seat})
})
<form method="POST" action="confirm.php">
<div align="center"><input type="Submit" id="btnsubmit" value="Submit" /></div>
</form>
And this is my php code.
$seat = "";
if(isset($_POST['seat']))
{
$seat = $_POST["seat"];
print_r($seat);
}
When this is executed I get the window alert,but the values stored in the array does not pass to the php file.Is there something wrong with this code?Please help!I'm stuck here!!!
$_POST isn't a built-in method, and jQuery doesn't provide a method like that either-- you can't just "set" the values into the $_POST array like this.
To post using jQuery, you would do something like the following, including a handler for data returning from the server (if you have any):
$.post("confirm.php", { seat: seat})
.done(function(data){
alert('Received data from server: ' + data);
});
You need to send the data to your PHP script, this does nothing in your JS code:
$_POST('confirm.php', {seat: seat})
use something like jQuery post method or vanilla JS XMLHttpRequest
I have the following JS code
var existingMenus = document.getElementsByClassName('multiSelectMenu');
for (var i = 0; i < existingMenus.length; i++) {
var existingMenu = existingMenus[i];
var existingMenuHTML = [];
var targetChildren = existingMenu.parentElement.nextElementSibling.children;
console.log(targetChildren)
// Here I'm adding +1 to the ID as it appears starting at zero with a styled checkbox does not work correctly
for (var x = 0; x < targetChildren.length; x++) {
if (targetChildren[x].selected) {
existingMenuHTML += '<li><input class="dropdown-input" type="checkbox" id="' + (x + 1) + '" data-label="' + targetChildren[x].textContent + '" checked="true"/><label class="multiLabel" for="' + (x +
1) + '"><span></span> ' + targetChildren[x].textContent + ' </label></li>';
} else {
existingMenuHTML += '<li><input class="dropdown-input" type="checkbox" id="' + (x + 1) + '" data-label="' + targetChildren[x].textContent + '"/><label class="multiLabel" for="' + (x + 1) +
'"><span></span> ' + targetChildren[x].textContent + ' </label></li>';
}
}
existingMenu.innerHTML += existingMenuHTML;
console.log(existingMenuHTML)
var inputs = existingMenu.children;
console.log(inputs);
for (var w = 0; w < inputs.length; w++) {
var input = inputs[w].children[0];
console.log(input);
input.addEventListener('click', function() {
console.log('--------------')
console.log(event)
var targetElement = event.target || event.srcElement;
console.log(targetElement);
var elementParent = targetElement.parentElement.parentElement.parentElement;
console.log(elementParent)
if (!elementParent.classList.contains('open')) {
elementParent.className += ' open';
}
var multiList = elementParent.nextSibling.querySelector('[value="' + targetElement.dataset.label + '"]');
console.log(multiList)
// Subtracting one to account for the plus one I added above
var inputId = targetElement.id - 1;
if (targetElement.checked == true) {
multiList.selected = "selcted";
} else {
multiList.selected = "";
}
console.log('--------------')
});
}
}
The code works correctly on the first instance of the multiPick but all others on page trigger the first multiSelectMenu items even though I was clicking on the 3rd multiSelectMenu on page.
Here is a screen shot of the console,
Here is a code pen, https://jsfiddle.net/6s3rc8d7/ When you click the 'label' and not the checkbox it has the same issue I am seeing.
The reason behind getting the different event.target in your fiddle is due to the below code snippet in your html.
<input class="dropdown-input" type="checkbox" id="1" data-label="English only">
<label class="multiLabel" for="1"><span></span> English only </label>
you can see that in the label element, you have the for attribute which contains the id of the input element. The functionality of for attribute is that the value of this identifies which form element a label is bound to. When you click on the label it will simulate the click event of the bounded element. This is why when you click the label , in your script the event.target is the input the label is bonded with.
More on for attribute you can read here. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label
I was able to rework the code and added the EventListener to the label instead of the checkbox.
I am using Plugin Form Validation to validate the form. And this plugin is working awesome.
But i am facing issue in validating dynamically generated inputs.
Below code is used to generate input fields dynamically
$("#countaccmp").change(function() {
var selVal = $(this).val();
$("#textboxDiv").html('');
if(selVal > 0) {
for(var i = 1; i<= selVal; i++) {
$("#textboxDiv").append('<input type="text" name="accmp'+i+'"
id="accmp'+i+'" class="form-control " />');
}
}
})
I tried validating with plugin as below:
$('#form').formValidation({
//--------- Plugin Validator Method -----------//
})
.on('change', '[name="countaccmp"]', function(e) {
//---- Wrote validation here, It works(only on change) but form is getting submitted
even after error ----//
$('.dynDiv').each(function(){
var input = $(this).children('input');
var dynField =
($(this).find("input[name^='accmp']").attr('name'));
if(input.val() == '' || input.val() == undefined){
alert("Error");
return false;
}
})
.on('success.form.fv', function(e) {
//---- Wrote validation here, It works but form is getting
submitted even after error ----//
Same Validation As above
})
Please let me know solution.
You should add your inputs to the plugin in order to be validated.
To do so, use the addField method, see bellow:
$("#countaccmp").change(function () {
var selVal = $(this).val();
$("#textboxDiv").html('');
if (selVal > 0) {
for (var i = 1; i <= selVal; i++) {
var input = ''
+ '<div class="form-group">'
+ ' <label class="col-sm-3 control-label" for="accmp' + i + '">Accmp ' + i + '</label>'
+ ' <div class="col-sm-5">'
+ ' <input type="text" name="accmp' + i + '" id = "accmp' + i + '" class = "form-control " / >'
+ ' </div>'
+ '</div>';
$("#textboxDiv").append(input);
$('#defaultForm').formValidation('addField', 'accmp' + i, {
validators: {
// Here, add your field validators.
}
});
}
}
});
Demo:
http://jsfiddle.net/Arkni/fpps1dqn/
References:
addField documentation: http://formvalidation.io/api/#add-field
Example using addField: http://formvalidation.io/examples/adding-dynamic-field/
I am having an issue with .val() returning an unexpected output I am using an item in an array to create a selector for an ID of a number input and then retrieving its value.
The input this should point to:
<div class="form-group col-xs-4">
<label>Strength</label>
<input class="attributes form-control" id="strength" type="number" min="1" max="300" value="50" />
</div>
javaScript / jQuery:
$.each(traitName, function (key, value) {
if (binConv(traitRaces[key], 12).charAt(race) + binConv(traitClasses[key], 4).charAt(baseClass) == 00 && $("#startrunes li[data-value='" + key + "']").length <= 0) {
$("#startrunes")
.append($("<li title='Costs:" + traitCost[key] + " Requirement: " + traitRequireStat0[key] + "" + traitRequireValue0[key] + "' data-cost='" + traitCost[key] + "' data-value='" + key + "' class='ui-widget-content'></li>")
.text(value));
}
else if (binConv(traitRaces[key], 12).charAt(race) + binConv(traitClasses[key], 4).charAt(baseClass) != 00) {
$("#startrunes li[data-value='" + key + "']").remove();
}
if (traitRequireStat0[key].length > 0) {
alert(parseInt($('#' + traitRequireStat1[key]).val(),10));
if ($('#'+traitRequireStat0[key]).val() < traitRequireValue0[key]) {
$("#startrunes li[data-value='" + key + "']").remove();
}
}
else if (traitRequireStat1[key].length > 0) {
if ($('#' + traitRequireStat1[key]).val() < traitRequireValue1[key]) {
$("#startrunes li[data-value='" + key + "']").remove();
}
}
The alert in the jQuery return NaN if I alert the val without parse int it comes back as undefined and if I use .text() I get random code all the arrays in here are equivalent length arrays and I don't believe them to be the root of the issue I am trying to get the current user input value not the value attribute.
Edit: forgot to mention the environment is jQuery / Bootstrap / jQuery UI
You have to use .text() - cos it functions