bootstrap-3 tooltip doesn't flash accordingly to the js - if - condition - twitter-bootstrap-3

This is the code I use for register users into mysql db. And I'm using Twitter Bootstrap tooltips, for obtain the following:
initially, when the user hover over the textboxes, the string wrote in the title attribute will be displayd.
if he will write only 2 letters (fe, for the firstname), and presses the submit button, the form won't be submitted, and the new tooltip message should flash and show: "Please use at least 3 letters!".
the same algorithm for every input in form.
if the user fills in correctly all the textboxes, then the form will be submitted to register.php, which will process the data.
<form id="form">
<div class="form-group">
<input type="text" class="form-control" id="firstname" placeholder="First Name" style="width:48%;float:left;" title="The First Name is mandatory! Please use at least 3 letters!"/>
<input type="text" class="form-control" id="lastname" placeholder="Last Name" style="width:48%;float:right;" title="The Last Name is mandatory! Please use at least 3 letters!"/>
<div style="clear:both;"></div>
</div>
<div class="form-group">
<input type="number" class="form-control" id="cnp" placeholder="CNP" title="The CNP is mandatory! Please use exact 13 numbers!"/>
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" placeholder="Password" style="width:48%;float:left;" title="The Password is mandatory! Please use at least 6 chars!"/>
<input type="password" class="form-control" id="password_again" placeholder="Retype the Password" style="width:48%;float:right;" title="This field must be the same as Password field"/>
<div style="clear:both;"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" placeholder="E-mail" title="The Email is mandatory!"/>
</div>
<div class="form-group text-center">
<button class="btn btn-default">Register</button>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#firstname').tooltip();
$('#lastname').tooltip();
$('#cnp').tooltip();
$('#password').tooltip();
$('#password_again').tooltip();
$('#email').tooltip();
$('#form').on('submit', function(e){
var firstname = $('#firstname').val().trim();
var lastname = $('#lastname').val().trim();
var cnp = $('#cnp').val().trim();
var password = $('#password').val().trim();
var password_again = $('#pssword_again').val().trim();
var email = $('#email').val().trim();
if (firstname != '' && firstname.length > 3 && lastname != '' && lastname > 3 && cnp != '' && cnp.length == 13 && password != '' && password.length >= 6 && password_again == password && email != ''){
$.ajax({
type: "POST",
url: "php/register.php",
data: {firstname: firstname, lastname: lastname, cnp: cnp, password: password, email: email},
success: function(response){
$('#content').html(response);
}
});
} else {
if (firstname.length < 3) {
$('#firstname').tooltip('show',function(){
title: "Please use at least 3 letters!"
});
}
}
e.preventDefault();
});
});
</script>
Problems:
When the user doesn't put the expected data (fe, at least 3 letters), the tooltip isn't changing accordingly (fe, Please use at least 3 letters!).
When the user does put the expected data, then for an unknown reason, the form isn't submitted!
Any suggestion? Thank you!

Add text to tooltip dynamically - with var:
var msg = '';
msg = 'Please use at least 3 letters';
and clear the message before that;
var msg = '';
if (firstname.length < 3) {
msg = Please use at least 3 letters;
$('#firstname').tooltip('show',function(){
title: msg
});
}
remove e.preventDefault(); - put it in the part when error occur, as it prevents the default event, ie: submit.
Edit:
$(document).ready(function(){
$('#firstname').tooltip();
$('#lastname').tooltip();
$('#cnp').tooltip();
$('#password').tooltip();
$('#password_again').tooltip();
$('#email').tooltip();
var msg = '';
$('#form').on('submit', function(e){
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
var cnp = $('#cnp').val();
var password = $('#password').val();
var password_again = $('#pssword_again').val();
var email = $('#email').val();
if (firstname != '' && firstname.length > 3 && lastname != '' && lastname > 3 && cnp != '' && cnp.length == 13 && password != '' && password.length >= 6 && password_again == password && email != ''){
$.ajax({
type: "POST",
url: "php/register.php",
data: {firstname: firstname, lastname: lastname, cnp: cnp, password: password, email: email},
success: function(response){
$('#content').html(response);
return true;
}
});
} else {
if (firstname.length < 3) {
msg = 'Please use at least 3 letters!';
$('#firstname').tooltip('show',function(){
title: msg
});
}
e.preventDefault();
}
});
});

Related

Razor Pages Display Validation for Hidden Input

I am attempting to provide user friendly input (as a percentage) for a decimal and be able to validate. I am stuck because the asp-validation-for will not display if the associated input is hidden.
Current technique is to use autonumeric.js for the client side formatting on a display only field that gets copied into the field to be saved to db.
How can I get validation message to display?
LoanEstimate.cs
[NotMapped]
public string RateDisplayOnly { get; set; }
[Range(0,1,ErrorMessage="Rate must be between 0.000% and 100.00%")]
[DisplayFormat(DataFormatString = "{0:p}")]
[Required]
public decimal? Rate { get; set; }
Create.cshtml
<div class="form-group">
<label asp-for="LoanEstimate.Rate" class="control-label"></label>
<input asp-for="LoanEstimate.RateDisplayOnly" class="form-control autonumeric-display-only autonumeric-percent" />
<input asp-for="LoanEstimate.Rate" class="form-control" type="hidden"/>
<span asp-validation-for="LoanEstimate.Rate" class="text-danger"></span>
</div>
Javascript
$(document).ready(function ($) {
//autonumeric.js field formatting
const anElement = AutoNumeric.multiple('.autonumeric-currency', {
currencySymbol: "$"
});
const anElement2 = AutoNumeric.multiple('.autonumeric-percent', {
decimalPlaces: 3,
rawValueDivisor: 100,
suffixText: "%"
}
)
$(".autonumeric-display-only").on('keyup', function () {
var str = this.id
var getThis = str.substring(0, str.indexOf("DisplayOnly"))
$("#" + getThis).val(AutoNumeric.getNumericString("#" + this.id));
});
});
ProblemValidation message does not display when input for LoanEstimate.Rate is hidden
Note: here is it displaying properly when not hidden
Use $.validator.setDefaults,here is a demo:
View:
<form method="post">
<div class="form-group">
<label asp-for="Rate" class="control-label"></label>
<input asp-for="RateDisplayOnly" class="form-control autonumeric-display-only autonumeric-percent" onblur="validateRate()"/>
<input asp-for="Rate" class="form-control" hidden />
<span asp-validation-for="Rate" class="text-danger"></span>
</div>
<input type="submit" value="submit" />
</form>
js:
function validateRate() {
$("#Rate").valid();
}
$.validator.setDefaults({
ignore: [],
// other default options
});
$(document).ready(function ($) {
//autonumeric.js field formatting
const anElement = AutoNumeric.multiple('.autonumeric-currency', {
currencySymbol: "$"
});
const anElement2 = AutoNumeric.multiple('.autonumeric-percent', {
decimalPlaces: 3,
rawValueDivisor: 100,
suffixText: "%"
}
)
$(".autonumeric-display-only").on('keyup', function () {
var str = this.id
var getThis = str.substring(0, str.indexOf("DisplayOnly"))
$("#" + getThis).val(AutoNumeric.getNumericString("#" + this.id));
});
});
result:

Error mesage quickly displaying then hiding as expected in VUE

I have a page which I validate the email add input #blur. This works perfectly and displays the error message if it fails validation rules set but the issue I have is that due to the #blur, when I click my reset button the error quickly displays then hides and this is poor UI and I want to stop it but can't figure out how to.
HTML
<div class="card" v-on:click="select($event)">
<div class="card-body">
<div class="form-group row">
<label class="col-sm-3 col-form-label pr-0" for="emailAddField">Email <span class="text-danger">*</span></label>
<div class="col-sm-9">
<div class="input-group">
<input id="emailAddField" ref="pdEmailAdd" class="form-control" type="search" :value="pdEmailAdd" #input="pdEmailAddInput" #blur="emailInputValChecker($event)" placeholder="Enter an email address">
<div class="input-group-append" :class="emailButtonValidation">
<a class="btn input-group-text primaryBtn" :class="emailButtonValidation" type="button" :href="'mailto:' + pdEmailAdd">
<i class="far fa-envelope"></i>
</a>
</div>
</div>
<div v-if="emailFormatErrorMsg" class="text-danger">Incorrect email address format</div>
</div>
<div class="card-footer">
<button id="resetButton" ref="resetButton" class="btn btn-warning col-4" #click="pdInitPageStates($event)" :disabled="resetDetails">
Reset details
</button>
</div>
</div>
I have 'hacked' at the card trying to use #click on the card to get the id but this didn't work so I set the id in my `data but not happy about it and sure there is a lot better way but I just can't figure it out
Code
data() {
return {
pdEmailAdd: '',
reg: /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,24}))$/,
detailsChanged: false,
emailIncorrectFormat: false,
targetId: 'resetButton', // HACK
targetId2: '', // HACK
}
},
computed: {
emailButtonValidation() {
if (!this.pdEmailAdd || !this.reg.test(this.pdEmailAdd)) {
if (this.pdEmailAdd === '') {
this.emailIncorrectFormat = false;
} else {
this.emailIncorrectFormat = true;
}
return 'disabled'
} else {
this.emailIncorrectFormat = false;
return ''
}
},
resetDetails() {
this.detailsChanged = false;
if (this.pdName != this.$store.state.account.firstname + ' ' + this.$store.state.account.lastname) {
this.detailsChanged = true;
}
if (this.telNoType === 'ddi' && this.pdTelNo != this.$store.state.account.ddi) {
this.detailsChanged = true;
} else if (this.telNoType === 'mobile' && this.pdTelNo != this.$store.state.account.mobile) {
this.detailsChanged = true;
} else if (this.telNoType === 'na' && this.pdTelNo != '') {
this.detailsChanged = true;
}
if (this.pdExtNo != this.$store.state.account.extension) {
this.detailsChanged = true;
}
if (this.pdEmailAdd != this.$store.state.user.adminemail) {
this.detailsChanged = true;
}
return !this.detailsChanged;
}
}
// Another hack to try set it soon as page loads
mounted() {
this.$refs.resetButton.click();
},
methods: {
emailInputValChecker(event) {
this.emailFormatErrorMsg = false;
if (!this.pdEmailAdd || !this.reg.test(this.pdEmailAdd)) {
if (this.pdEmailAdd === '') {
this.emailFormatErrorMsg = false;
} else {
this.select(event)
// Uses the 'dirty hacks'
if (this.targetId !== '' && this.targetId !== 'resetButton' && this.targetId2 !== 'resetButton') {
this.emailFormatErrorMsg = true;
};
}
}
},
select(event) {
this.targetId = event.target.id;
if (this.targetId === 'resetButton') {
this.targetId2 === 'resetButton';
} else if (this.targetId === '') {
this.targetId === 'resetButton';
}
}
}
Basically all I want is the input to check it passes validation when input is left unless the reset button is clicked then ignore it but think I've gone code blind and can't think of a way to do this.
The mousedown event on your reset button is what causes blur on the input to fire. Adding #mousedown.prevent to the reset button will stop that from happening specifically when the reset button is clicked.
This snippet ought to illustrate the solution. Remove #mousedown.prevent from the reset button and you'll see similar behavior to your issue, with the error briefly flashing.
new Vue({
el: '#app',
data: {
email: '',
error: null
},
methods: {
onBlur () {
if (this.email === 'bad') {
this.error = 'bad email!'
} else {
this.error = null
}
},
onReset () {
this.error = null
this.email = ''
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button #click="onReset" #mousedown.prevent>Reset</button>
<p>
Type in "bad" and leave input to trigger validation error<br>
<input type="text" v-model="email" #blur="onBlur"/>
</p>
<p>{{ email }}</p>
<p v-if="error">error!</p>
</div>

Updating v-model data in form inputs with a series of methods in a Vuetify project?

I am attempting to update a series of v-text-fields (type='number') so that after the user has entered in a numeric value, the number shown in the input will be updated with commas (so a value of 5032 would become 5,032 for example). I found this article and was able to accomplish what I'm after with a single input using the example provided...
Markup:
<div id="app">
<div v-if="visible === true">
Enter Amount: <br>
<input type="number"
v-model="amount"
placeholder="Enter Amount"
#blur="onBlurNumber"/>
</div>
<div v-if="visible === false">
Enter Amount: <br>
<input type="text"
v-model="amount"
placeholder="Enter Amount"
#focus="onFocusText"/>
</div>
Script:
data: {
amount: null,
temp: null,
visible: true
},
methods: {
onBlurNumber() {
this.visible = false;
this.temp = this.amount;
this.amount = this.thousandSeprator(this.amount);
},
onFocusText() {
this.visible = true;
this.amount = this.temp;
},
thousandSeprator(amount) {
if (amount !== '' || amount !== undefined || amount !== 0 || amount !== '0' || amount !== null) {
return amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return amount;
}
}
}
...but I want to make the methods generic enough to work with any numeric v-text-fields I am using. I have been able to update a parameter value within my methods, but have been unable to actually update the v-model data of the v-text-field.
Markup:
<div id="app">
<div v-if="visible === true">
<v-text-field
class="mb-3 d-inline-block"
type="number"
prepend-inner-icon="attach_money"
v-model="amount"
label="Amount"
mask="##########"
outline
:rules="[v => !!v || 'Amount is required']"
#blur="onBlurNumber(amount)"
required>
</v-text-field>
</div>
<div v-if="visible === false">
<v-text-field
class="mb-3 d-inline-block"
prepend-inner-icon="attach_money"
v-model="amount"
label="Amount"
outline
#focus="onFocusText(amount)"
>
</v-text-field>
</div>
Script:
onBlurNumber(data) {
this.visible = false;
this.temp = data;
data = this.thousandSeprator(data);
},
onFocusText(data) {
this.visible = true;
data = this.temp;
},
I can log the value of data in these methods and confirm that the commas are being applied correctly, but now I don't know how to send the data value back to update the v-text-field's v-model. I experimented with selecting the v-text-field using a ref value but the ref turns up as an undefined value when the method is triggered.
Does anyone know how I can update the v-model of the v-text-field using arguments in this sort of fashion so the methods are reusable?
I assume that you have multiple data items for each of the text fields:
data: function() {
return {
// Field 1
temp1: null,
amount1: null,
visible1: true,
// Field 2
temp2: null,
amount2: null,
visible2: true
}
}
In your markup, when calling the method you could then pass the name of the property, or maybe its suffix.
<v-text-field #blur="onBlurNumber('2')"
And in your script, you could update the data items by using dynamic properties:
methods: {
onBlurNumber(suffix) {
this["visible" + suffix] = false;
this["temp" + suffix] = this["amount" + suffix];
this["amount" + suffix] = this.thousandSeprator(this["amount" + suffix]);
},
Here's a working example of two independent text inputs that are calling the same methods to achieve this. We could refactor this to reduce the number of data items using arrays if needed.

Watin. how to show invinsible class

HTML code:
<div class="col-sm-9">
<input name="NewCardOrAccountNumber" class="form-control ui-autocomplete-input" id="NewCardOrAccountNumber" type="text" value="" autocomplete="off">
<span class="ui-helper-hidden-accessible" role="status" aria-live="polite"></span>
</div>
<div class="unvisible" id="clientInfoNew">
<div class="form-group">
<label class="col-sm-3 control-label">FIRST NAME</label>
<div class="col-sm-9" id="FnameNew"></div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">LAST NAME</label>
<div class="col-sm-9" id="LnameNew"></div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">BIRTH DATE</label>
<div class="col-sm-9" id="BirthDateNew"></div>
</div>
Watin code:
[TestMethod]
[TestCategory("Rimi Change card page")]
public void Rimi_4444_Change_Card_and_Assert()
{
//Web Address
using (IE ie = new IE(this.Rimi))
{
//IE ie = new IE(RimiChangeCard);
ie.BringToFront();
ie.ShowWindow(WatiN.Core.Native.Windows.NativeMethods.WindowShowStyle.Maximize);
ie.TextField(Find.ById("NewCardOrAccountNumber")).TypeText("9440385200600000020");
If I write card number from keyboard, the invisible class appear, and you can see FIRST NAME, LAST NAME and so on. But if I do this with watin, it does not appear, and you only see card number which you input. Its like hidden fields of information. I do not know how to make that I could see this fields when I input card number.
There would be a JavaScript function, which gets executed when you manually enter the data in the text field.Go through the Java Script functions on the same page which refer to that element using it's ID NewCardOrAccountNumber.
Refer to this link for sample application. Where msg_to is element, and has a KeyUp event associated. When that filed gets a , value, there is a div section inside which a `Subject' field is shown.
Similarly, after executing the TypeText, try to trigger related event mentioned in the Java Script event using Java script execution.
EDIT: I see that the javascript functions gets executed after bulr event is fired. This means the textbox field should loose the focus. Try the below options.
// 1. Try focusing out of control.
ie.TextField(Find.ById("NewCardOrAccountNumber")).TypeText("9440385200600000020");
ie.TextField(Find.ById("OldCardOrAccountNumber")).Click();
ie.WaitForComplete();
// 2. Try Using Send Keys method to tab out.
ie.TextField(Find.ById("NewCardOrAccountNumber")).TypeText("9440385200600000020");
System.Windows.Forms.SendKeys.SnedWait("{TAB}"); // Need to add System.Windows.Forms reference to the project.
I put image on the internet, so click on this link Image and you will see on first image how look page, second picture - what have to happen when you input card number (from keyboard), third - what happen when card namuber is input from watin (does not appear information about card).
HTML code:
<div class="ibox-content">
<br>
<div class="form-horizontal">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<label class="col-sm-3 control-label">NEW CARD</label>
<input name="NewCardId" id="NewCardId" type="hidden" value="0" data-val-required="The NewCardId field is required." data-val-number="The field NewCardId must be a number." data-val="true">
<div class="col-sm-9"><span class="ui-helper-hidden-accessible" role="status" aria-live="polite"></span><input name="NewCardOrAccountNumber" class="form-control ui-autocomplete-input" id="NewCardOrAccountNumber" type="text" value="" autocomplete="off"></div>
</div>
<div class="unvisible" id="clientInfoNew">
<div class="form-group">
<label class="col-sm-3 control-label">FIRST NAME</label>
I maybe find what you looking for Sham, but I do not know how to use it :
<script type="text/javascript">
$(document).ready(function() {
var NewCardId = "#NewCardId";
var OldCardId = "#OldCardId";
var NewCardNumber = "#NewCardOrAccountNumber";
var OldCardNumber = "#OldCardOrAccountNumber";
$(NewCardNumber).autocomplete(
{
source: function(request, response) {
$.ajax({
url: '/LoyaltyWebApplication/Suggestion/GetCardSuggestions',
dataType: "json",
data: {
str: $(NewCardNumber).val()
},
success: function(data) {
response($.map(data, function(item) {
var label = "";
if (item.Fname != null) label += item.Fname;
if (item.Lname != null) label += " " + item.Lname;
if (label.trim() != '') label = " (" + label.trim() + ")";
return {
value: item.CardNumber,
label: item.CardNumber + label
}
}));
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
},
select: function(event, ui) {
getCardDetails($(NewCardNumber), $(NewCardId), 'newCardSegments', true);
$("#newCardSegments").hide();
$("#clientInfoNew").show();
},
minLength: 2
}).blur(function() {
getCardDetails($(NewCardNumber), $(NewCardId), 'newCardSegments', true);
});
$(OldCardNumber).autocomplete(
{
source: function(request, response) {
$.ajax({
url: '/LoyaltyWebApplication/Suggestion/GetCardSuggestions',
dataType: "json",
data: {
str: $(OldCardNumber).val()
},
success: function(data) {
response($.map(data, function(item) {
var label = "";
if (item.Fname != null) label += item.Fname;
if (item.Lname != null) label += " " + item.Lname;
if (label.trim() != '') label = " (" + label.trim() + ")";
return {
value: item.CardNumber,
label: item.CardNumber + label
}
}));
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
},
select: function(event, ui) {
getCardDetails($(OldCardNumber), $(OldCardId), 'oldCardSegments', false);
$("#oldCardSegments").hide();
},
minLength: 2
}).blur(function() {
getCardDetails($(OldCardNumber), $(OldCardId), 'oldCardSegments', false);
});
function getCardDetails(cardNumHolder, cardIdHolder, segmentTablePlace, isNew) {
$.getJSON('/LoyaltyWebApplication/LOV/SetId?lovType=ReplacementLOV&lovValue=' + cardNumHolder.val(), null,
function(data) {
$("#clientInfo" + ((isNew) ? "New" : "Old")).show();
if (cardNumHolder.val() == '') {
return;
}
var i;
for (i = 0; i < data.otherNames.length; i++) {
$("#" + data.otherValues[i] + (isNew ? "New" : "Old")).text(data.otherNames[i]);
}
cardIdHolder.val(data.Id);
$.getJSON('/LoyaltyWebApplication/Replacement/ClientSegmentsList?clientId=' + data.Id + "&no_cache=" + Math.random, function(data) {
$("#" + segmentTablePlace).find('tbody').empty();
if (data.length > 0) {
$.each(data, function(index) {
$("#" + segmentTablePlace).find('tbody').append("<tr><td>" + data[index].SegmentCode + "</td><td>" + data[index].SegmentName + "</td></tr>");
});
$("#" + segmentTablePlace).show();
}
});
});
}
$("#resetVal").click(function() {
$("#NewCardOrAccountNumber").attr("value", "");
$("#NewCardOrAccountNumber").val("");
$("#NewCardId").attr("value", "");
$("#NewCardId").val("");
$("#clientInfoNew").hide();
$("#OldCardOrAccountNumber").attr("value", "");
$("#OldCardOrAccountNumber").val("");
$("#OldCardId").attr("value", "");
$("#OldCardId").val("");
$("#clientInfoOld").hide();
return false;
});
});
</script>

How to get value from YUI3 autocomplete to another input

Using YUI3 and try appending the email part of the search value to another input field.
Everything working fine but don't know how to add the email value to the new input field.
Right now I just appending the value to the body.
Thanks full for any help
Here is my code:
<script type="text/javascript">
YUI().use("autocomplete", "autocomplete-highlighters","autocomplete-filters", "node"
function (Y) {
var anInput= Y.one('#searchUser').plug(Y.Plugin.AutoComplete, {
minQueryLength: 0,
scrollIntoView: true,
circular: false,
activateFirstItem: true,
resultHighlighter: 'phraseMatch',
resultFilters: 'charMatch',
resultListLocator: 'user',
resultTextLocator: function (result_) {
return result_.firstname+ ' ' + result_.lastname+ ' ' + result_.email;
},
source: 'http://localhost:8080/rest/user/jsonp?callback={callback}',
});
anInput.ac.on('select', function (ev) {
Y.one('#email').append('<div>User Email: ' + ev.result.raw.email + '</div>');
});
});
</script>
And here is the HTML:
<input id="searchUser" type="text" class="search" name="searchUser" size="40" value="Enter keywords..." onfocus="if(!this._haschanged){this.value=''};this._haschanged=true;" >
<div id="email">
<input id="email" type="text" name="email" size="40" >
</div>
Here is the problem, I can't get the email value added to the input field
Thanks for any help!
Y.one('#email').set('value', ev.result.raw.email);
https://yuilibrary.com/yui/docs/node/properties.html