Checking whether a input element value contains a certain string - javascript

I need to check whether or not a input element's value(typed by the user into the box) returned from
$("#emailInput").css("value")
contains a certain string.
I have tried various methods seen on google but none have worked.
The HTML:
<form class="form-horizontal" role="form">
<div id="emailBorder">
<label id="emailStyle">Email address:</label>
<div id="emailInputStyle">
<input class="form-control" id="emailInput" type="text">
<span id="emailGlyphicon"></span>
</div>
</div>
<div class="form-group">
<label id="contentStyle">Content:</label>
<div id="contentInputStyle">
<textarea class="form-control" rows="5" id="contentInput"></textarea>
</div>
</div>
<button type="submit" id="sendStyle" class="btn btn-default">Send</button>
</form>
The Javascript (My Attempt):
$("#emailInput").change(function () {
if ($("#emailInput").css("value").contains("#") && $("#emailInput").css("value").contains(".")) {
// do something
} else {
// do something else
}
});

Instead of css(), use val(). Also, instead of contains() use indexOf() because contains() works on jQuery DOM objects, not strings
$("#emailInput").change(function() {
if ($("#emailInput").val().indexOf("#") > -1 && $("#emailInput").val().indexOf(".") > -1) {
console.log('It contains # and .');
} else {
// do something else
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form class="form-horizontal" role="form">
<div id="emailBorder">
<label id="emailStyle">Email address:</label>
<div id="emailInputStyle">
<input class="form-control" id="emailInput" type="text">
<span id="emailGlyphicon"></span>
</div>
</div>
<div class="form-group">
<label id="contentStyle">Content:</label>
<div id="contentInputStyle">
<textarea class="form-control" rows="5" id="contentInput"></textarea>
</div>
</div>
<button type="submit" id="sendStyle" class="btn btn-default">Send</button>
</form>
css() will get/set the inline style of an element. val() will get/set the value of an input type element

You can try this:
$("#emailInput").change(function () {
if ($this.contains("#") && $this.contains(".")) {
// do something
} else {
// do something else
}
});

Related

html form: action page doesn't see element added dinamically with js

I wrote a code to add dinamically elements in a form with js. when i submit data, action page says that index of this element are undefined
I have this form:
<form action="testRicetta.php" method= "POST" >
[...]
<ul id ="passi" >
<li id ="li_passo0">
<div class="row">
<div class="col-25">
<label for="descrizione">Passo 0</label>
</div>
<div class="col-75">
<textarea id="passo0" name="passo0" placeholder="Descrivi
il passo" style="height:100px" required ></textarea>
<input type="file" id="immagine_0" name="immagine" >
</div>
</div>
</li>
</ul>
<button id="addMore" >Aggiungi passo</button>
This is the js code where appear the listener of button #addMore
var passi = 1;
$(function() {
$("#addMore").click(function(e)
{
e.preventDefault();
$("#passi").append(`<li id ="li_passo"`+passi+`>
<div class="row">
<div class="col-25">
<label for="passo"`+passi+`>Passo `+passi+`</label>
</div>
<div class="col-75">
<textarea id="passo"`+passi+` name="passo"`+passi+`
placeholder="Descrivi il passo" style="height:100px"
required ></textarea>
<input type="file" id="immagine_"`+passi+`
name="immagine" >
</div>
</div>
</li>`);
passi++;
},
$('.sel').chosen());
})
action page:
echo $_POST{passo0];
echo $_POST{passo1];
Result:
Notice: Undefined index: passo1
Furthermore, is possibile read data in a loop? i tried this
for($i = 0; isset($_POST['passo'+$i]);$i++)
echo $_POST['passo'+$i];
but i get this error:
Warning: A non-numeric value encountered in (the loop)
So how can i read this data, and how can do it with a loop?
When your adding the new field, you are concatenating the passi variable value outside the of name name="passo"'+passi+', it should be name="passo'+passi+'".
Try:
var passi = 1;
$(function() {
$("#addMore").click(function(e)
{
e.preventDefault();
$("#passi").append('<li id ="li_passo"'+passi+'>
<div class="row">
<div class="col-25">
<label for="passo"'+passi+'>Passo '+passi+'</label>
</div>
<div class="col-75">
<textarea id="passo"'+passi+' name="passo'+passi+'"
placeholder="Descrivi il passo" style="height:100px"
required ></textarea>
<input type="file" id="immagine_"'+passi+'
name="immagine" >
</div>
</div>
</li>');
passi++;
},
$('.sel').chosen());
})
And then:
echo $_POST[passo0];
echo $_POST[passo1];

jquery validate custom validation not working

$(document).ready(function () {
jQuery.validator.addMethod("insz", function (value, element) {
var insz = $('#txtINSZ').val()
var controle = parseInt(insz.substring(13, 15))
var getal = insz.substring(0, 2) + insz.substring(3, 5) + insz.substring(6, 8) + insz.substring(9, 12)
var rest = parseInt(getal) % 97
alert("we doin' this mun")
return 97 - rest == controle;
}, "* Amount must be greater than zero");
$('#form1').validate({
rules: {
txtINSZ: {
required: $('#cbInsz').prop('checked') == false,
insz: function () {
$('#cbInsz').prop('checked') == true;
}
}
},
showErrors: function (errorMap, errorList) {
this.defaultShowErrors();// to display the default error placement
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.js"></script>
<form method="post" action="#" id="form1" a="" novalidate="novalidate">
<div id="container">
<div class="container-fluid">
<div class="col-xs-12">
<div class="form-horizontal col-xs-4" id="divDimLeft">
<span id="lblTitleAlgemeen">Algemen Informatie</span>
<div class="checkbox" style="margin-left:20px;">
<span id="lblCheck">
<input type="checkbox" id="cbInsz" checked="">
INSZ nummer werknemer gekend?
</span>
</div>
<div class="form-group" id="divINSZ">
<span id="lblINSZ" class="required" for="txtINSZ" aria-required="true">INSZ-nummer gekend?</span>
<input name="ctl00$ContentPlaceHolder1$txtINSZ" type="text" maxlength="15" id="txtINSZ" class="form-control required form valid" oninput="autoInvullen()" aria-required="true" placeholder="__.__.__-___.__" aria-invalid="false" required=""><label id="txtINSZ-error" class="error" for="txtINSZ" style="display: none;"></label>
</div>
<div class="form-group">
<span id="lblNaam" class="required" for="txtNaam" aria-required="true">Naam</span>
<input name="ctl00$ContentPlaceHolder1$txtNaam" type="text" maxlength="40" id="txtNaam" class="form-control form requiredField error" aria-required="true" aria-invalid="true"><label id="txtNaam-error" class="error" for="txtNaam">Dit veld is verplicht.</label>
</div>
<div id="divButton" class="text-right" style="width: 87.5%">
<input type="submit" name="ctl00$ContentPlaceHolder1$btnSubmit" value="Volgende" id="btnSubmit" class="btn btn-primary col-xs-2" style="float: none; min-width:200px;">
</div>
</div>
</div>
</div>
</div>
</form>
I wanted to make a custom validator but for some reason it's not working at all. The required does work so there is no issue with finding the elements in my page. So is there someone who has any idea why it is not working?
Thans in advance, under here you find the code i'm using including the method I wrote and the start of the validate method.
You can't just insert a comparison operator all by itself as the parameter; you need a function that returns the value of this parameter, in this case a boolean from the comparison operator...
$('#form1').validate({
rules: {
txtINSZ: {
required: function() {
return $('#cbInsz').prop('checked') == false;
},
insz: function() {
return $('#cbInsz').prop('checked') == false;
}
....
Solved it, I just putted the rules out of the rules section. After the validation code I putted this:
$('#txtINSZ').rules("add", {
required:true,
insz:true
})
Works perfectly.
I also faced the same situation, but in my case below two steps worked.
use data-rule-insz="true" attribute on your HTML input element for which you want custom validation.
also add a name attribute as mentioned in the below example:-
<input id="customer" name="customer" data-rule-insz="true" required type="text" class="typeahead form-control" />

In angular form span can not be displayed

I am not able to see error message on clicking the submit button using angularjs.
Any lead will be appreciated
Thanks in advance :)
<form id="formbody" ng-submit="submituser(form)" name="form" novalidate>
<input type="text" ng-class="{ errorinput: submitted && form.dob.$invalid }" name="dob" ng-model="dob" placeholder="Date of Birth" required />
<span class="e" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
<div style="padding-left: 275px;">
<button type="submit">Submit</button>
<!-- <div type="button" id="btn" style="color: red;" >Submit</div> -->
</div>
</div>
</form>
.controller('ExampleController', function($scope, $location, $scope, $stateParams) {
$scope.singleSelect = '';
$scope.goToPage = function() {
console.log("selectservice");
$location.path("/selectservice");
}
$scope.submituser = function($scope) {
if ($scope.form.$valid) {} else {
$scope.submitted = true;
}
}
})
change ng-show of span to
<span class="e" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
please check the form name
you have used two different names
name ="form" in form tag and used as signUpForm.dob in input field.
Check your ng-model to
<form id="formbody" ng-submit="submituser(form)" name="signUpForm" novalidate>
<input type="text" ng-class="{ errorinput: submitted && signUpForm.dob.$invalid }" name="dob" ng-model="form.dob" placeholder="Date of Birth" required />
<span class="e" ng-if="submitted && signUpForm.dob.$invalid">Please provide a valid date of birth</span>
<div style="padding-left: 275px;">
<button type="submit">Submit</button>
</div>
</div>
</form>
.controller('ExampleController',function($scope,$location,$scope, $stateParams){
$scope.singleSelect='';
$scope.goToPage=function(){
console.log("selectservice");
$location.path("/selectservice");
}
$scope.submitted =false;
$scope.submituser = function(form){
// console.log(form);
if (form.$valid) {
your logic
} else {
$scope.submitted = true;
}
}
})
Try something like that
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form" ng-app>
<div class="control-group" ng-class="{true: 'error'}[submitted && form.dob.$invalid]">
<label class="control-label" for="dob">Your Date of Birth</label>
<div class="controls">
<input type="text" name="dob" ng-model="dob" required />
<span class="help-inline" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
</div>
</div>
<button type="submit" class="btn btn-primary btn-large" ng-click="submitted=true">Submit</button>
</form>
You have to provide the form name but even after that you cannot refer to your form in controller unless you pass it through the submit function arguments. Also there is not signupForm() function in your controller.
The way to go is :
<form id="formbody" name="myForm" ng-submit="signupForm(myForm)" novalidate>
<!-- inputs etc -->
</form>
Then based on submituser():
$scope.signupForm = function(myForm) {
//Do whatever you want to do
if(myForm.$valid) {
//some logic
}else {
$scope.submitted = true;
}
}
On the other hand if you don't want to mess up with the controller you can always use FormController method $submitted. This would look like:
<span class="e" ng-show="myForm.$submitted && myForm.dob.$invalid">Please provide a valid date of birth</span>

Do not submit form before jquery validate is okay

I am looking for a way, so that my FormMethod.Post Dosen't submit, before jquery validation is done. I have tried by making it so that the button just is at disabled, and then remove disable on keydown, if form is okay. But that didn't work, and neither isn't secure. What can i do?
Html
#using (Html.BeginForm("_Kontakt", "Home", FormMethod.Post))
{
<div class="row">
<div class="col-sm-6">
<div class="col-sm-12">
<b>Facebook Url</b>
<input id="FacebookUrl" name="FacebookUrl" type="text" class="form-control" />
</div>
<div class="col-sm-12">
<b>Steam Url</b>
<input id="SteamUrl" name="SteamUrl" type="text" class="form-control" />
</div>
<div class="col-sm-12">
<button id="SendBtn" class="btn btn-success pull-right" onclick="return validateUrl();">Send</button>
</div>
</div>
</div>
}
Jquery/Javascript
function validateUrl() {
facebookURL = $("#FacebookUrl").val();
steamURL = $("#SteamUrl").val();
var facebook = /^(?:(?:http|https):\/\/)?(?:www.)?facebook.com\/(?:(?:\w)*#!\/)?(?:pages\/)?(?:[?\w\-]*\/)?(?:profile.php\?id=(?=\d.*))?([\w\-]*)?$/;
var steam = /(?:https?:\/\/)?steamcommunity\.com\/(?:profiles|id)\/[a-zA-Z0-9]+/;
if (facebook.test(facebookURL)) {
}
else {
alert("Ikke et facebook gyldigt url!");
}
if (steam.test(steamURL)) {
}
else {
alert("Ikke et steam gyldigt url!");
}
return facebook.test(facebookURL);
return steam.test(steamURL);
}
ANSWERE
return facebook.test(facebookURL) && steam.test(steamURL);
There is an "onsubmit" event that allows you to control form submission http://www.w3schools.com/tags/ev_onsubmit.asp
If you put the inputs and button in a form element and use the pattern and required attributes in combination with the :invalid selector the browser can do the validation for you:
/* Add the .focused class when the user focuses
an input to only show the error message once */
$("#the-form input").focus(function(){
this.classList.add("focused");
});
.input-error-message {
color: red;
}
/* Show elements with the class .input-error-message
if they come after an input with invalid data if the
user isn't typing or if it has not been focused yet */
:invalid:not(:focus).focused + .input-error-message {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<form class="col-sm-6" id="the-form" onsubmit="return isValid()">
<div class="col-sm-12">
<b>Facebook Url</b>
<input id="FacebookUrl" name="FacebookUrl" type="text" class="form-control" pattern="^(?:(?:http|https):\/\/)?(?:www.)?facebook.com\/(?:(?:\w)*#!\/)?(?:pages\/)?(?:[?\w\-]*\/)?(?:profile.php\?id=(?=\d.*))?([\w\-]*)?$" required/>
<div class="input-error-message" hidden>Ikke et facebook gyldigt url!</div>
</div>
<div class="col-sm-12">
<b>Steam Url</b>
<input id="SteamUrl" name="SteamUrl" type="text" class="form-control" pattern="(?:https?:\/\/)?steamcommunity\.com\/(?:profiles|id)\/[a-zA-Z0-9]+" required/>
<div class="input-error-message" hidden>Ikke et steam gyldigt url!</div>
</div>
<div class="col-sm-12">
<button id="SendBtn" class="btn btn-success pull-right">Send</button>
</div>
</form>
</div>

Jquery - find next element in each loop

I have a question like so.
I have HTML structure:
<form id="form">
<div class="row">
<div class="item-input">
<label for="A1">A1</label>
<input type="text" name ="A1" />
<span class="input-require">(*)</span>
<span class="info">(Enter A1)</span>
</div>
<div class="item-input">
<label for="A2">A2</label>
<input type="text" name ="A2" />
<span class="input-require">(*)</span>
<span class="info">(Enter A2)</span>
</div>
</div>
<div class="row">
<div class="item-input">
<label for="B1">B1</label>
<input type="text" name ="B1" />
<span class="input-require">(*)</span>
<span class="info">(Enter B1)</span>
</div>
<div class="item-input">
<label for="B2">B2</label>
<input type="text" name ="B2" />
<span class="input-require">(*)</span>
<span class="info">(Enter B2)</span>
</div>
</div>
...
</form>
Now I want to selected 'span' has class "info" behind input[type=text] each.
I try:
<script type="text/javascript">
$(document).ready(function() {
$("#form input[type=text]").each(function(){
var spanInfo = $(this).closest("item-input").next().find('span.info');
console.log(spanInfo.text()); // Result is empty
});
});
</script>
Why is empty? Help me please. How do I, thanks
var spanInfo = $(this).closest("item-input").next().find('span.info');
Should be
var spanInfo = $(this).closest(".item-input").next().find('span.info');
You are missing the . (dot, class)
Your mean is show "(Enter A2)" and "(Enter B2)" or show all 4 element value: (Enter A1), (Enter A2), (Enter B1), (Enter B2)
If only show 2 value then CODE HERE
else You want to show 4 value, you can code:
$(document).ready(function() {
$("#form input[type=text]").each(function(){
var spanInfo = $(this).closest(".item-input").find('span.info');
console.log(spanInfo.text());
});
});

Categories