How to restrict user from entering duplicate text in multiple text inputs - c#

i have a problem in my site user is filling a form and let suppose there are two textboxes in that form, I want to do that if user enter "Ahsan" in first textbox then he is not allowed to enter "Ahsan" in second textbox.

Here is a quick example
$(function() {
$('#text1,#text2').change(function() {
if ($('#text1').val() === $('#text2').val()) {
alert('text matches');
}
});
});​
The code uses the .change() function to trigger a function on change of either text input (uses the multiple selector) and then compares the values using .val().
.change() could be .blur() or keyup() or performed on submit of the form using .submit()
Update
If you needed to check lots of inputs... then you could use .each() :
$(function () {
$('.inputclass').change(function () {
var $current = $(this);
$('.inputclass').each(function () {
if ($(this).val() == $current.val() && $(this).attr('id') != $current.attr('id')) {
alert('duplicate found');
}
});
});
});
this loops each value of inputs using the class inputclass and checks for duplicates

Try this:
$('#lastInput').keyup(function () {
if ($(this).val() === $('#firstInput').val()) {
$(this).val('');
}
});

you can do it something like that:
for example your first textbox id is txt1, and second textbox id is txt2.
you want to restrict 'Ahsan' to type in second textbox.
$(document).ready(function(){
var text1=$('#txt1').text();
var text2=$('#txt2').text();
if(text1!text2){
//do your code
}
else {
alert('value exist in textbox1');
}
})

$('input:text').not(':first').on('blur', function() {
var value = this.value;
if(value.length) {
$('input:text').not(this).each(function(){
if(this.value == value) {
alert('Error');
return false;
}
});
}
});

Related

JQuery client side continues even if invalid mvc 4

Script
$(document).ready(function () {
"use strict";
$.validator.unobtrusive.parse($("#form"));
$("#submit").on("click", function () {
var form = $("#form");
form.validate();
if (form.valid()) {
}
return false;
});
});
HTML
<span>Please enter the amount of orders you wish you process:</span>
<br>
#Html.TextBoxFor(m => m.OrderModel.AmountOfOrders, new {id = "AmountOfOrders"})
#Html.ValidationMessageFor(m=> m.OrderModel.AmountOfOrders)
<input type="submit" value ="Submit" id="submit" />
I seem to have a problem with the script. The DataAnnotations for C# are showing up on the View but even if required fields are empty it will still continue to the other page.
if your button is not given
type="button"
, it will default to
type="submit"
Considering that you are using a form, the form will get submitted by the button click as your javascript is executing.
Try this.
$("#submit").on("click", function (event) {
var form = $("#form");
form.validate();
if (form.valid()) {
}
else
{
event.preventDefault();
return false;
}
});
Always use the submit event for forms, not the click event. That way it will work with key-presses:
$("#submit").on("submit", function () {
var form = $("#form");
form.validate();
if (form.valid()) {
// Proceed with submit!
}
else {
// Stop submit!
return false;
}
});

How to hide a checkboxlist based on a dropdown selection using JQuery?

I have a form with a dropdownlist. Based on the selected item in the dropdown respective chekbox list appears and other checkboxlist disappears. How can you accomplish this using JQuery?
Here's Javascript that you should be able to easily adapt to your specific elements:
$('#dropdownlist').on('change', function () {
if ($(this).val()) {
if($(this).val() === "some value") {
$('#somecheckboxgroup').show();
$('#someothercheckboxgroup').hide();
}
else if($(this).val() === "some other value") {
$('#somecheckboxgroup').hide();
$('#someothercheckboxgroup').show();
}
}
});
Essentially, you just want to run a function every time the dropdownlist changes, and in it, check the currently selected value and then run your desired code based on the observed value.
Here is a really basic example - http://jsfiddle.net/jayblanchard/G8z3r/
The code can be shortened up just by using different selectors, id's and classes but I wanted to give you a basic idea on how this works.
$('select[name="showbox"]').change(function() {
if('foo' == $(this).val() ) {
$('div').hide(); // make sure all divs are hidden
$('#checkboxA').show(); // show the right one
} else if ('bar' == $(this).val() ) {
$('div').hide(); // make sure all divs are hidden
$('#checkboxB').show(); // show the right one
} else if ('both' == $(this).val() ) {
$('div').show(); // sow all divs
} else {
$('div').hide();
}
});

Set SELECT value after filling it with jQuery

I'm trying to populate a SELECT using jQuery and after it's populated set the value i want.
I'm working with ASP.NET MVC 5.
The problem is the value doesn't get set
Here's my code:
$(document).ready(function () {
//DropDownLists Initialization
ListCategories(); //Populates the dropdownlist
PreviousCategory(); //Sets DropDownList value to previous state (posted value)
});
function PreviousCategory() {
var previousCategory = $("#PreviousCategory").val();
if (previousCategory != null && previousCategory != '') {
$("#IdCategory").val(previousCategory);
}
}
$("#PreviousCategory") is a hidden input wich gets it's value server-side after a postback with the next code:
#if (ViewBag.Category!=null)
{
#Html.Hidden("PreviousCategory",(object)ViewBag.Category);
}
Both functions work separately, the DropDownList gets populated flawlessly, but the value doesn't get set.
If i trigger PreviousCategory() from another event (for example a button click), the value gets set perfectly.
I didn't think it was necessary to post ListCategories() code since it works well and you can just assume it fills the dropdownlist, though if anyone find it necessary let me know and i'll edit the post.
EDIT:
Here is ListCategories() code:
function ListCategories(){
_idOrganigrama = $("#IdOrganigrama").val()
_idTipoPedido = $("#IdTipoPedido").val()
data = { idOrganigrama: _idOrganigrama, idTipoPedido: _idTipoPedido }
$.post("ListCategories/", data, function (categoryList) {
$("#IdCategoria").empty();
$(categoryList).each(function () {
$("<option />", {
val: this.Id,
text: this.Descripcion
}).appendTo($("#IdCategory"));
});
});
}
By the way...$("#IdCategory") is the select.
The problem seems to be in the ListCategories where you might be using a async function like ajax to fetch data from server and populate the select.
So use a callback based solution like this
$(document).ready(function () {
//DropDownLists Initialization
ListCategories(PreviousCategory); //Populates the dropdownlist
//Sets DropDownList value to previous state (posted value) after the values are loaded
});
function PreviousCategory() {
var previousCategory = $("#PreviousCategory").val();
if (previousCategory != null && previousCategory != '') {
$("#IdCategoria").val(previousCategory);
}
}
function ListCategories(callback) {
//your ajax request to populate the select
$.ajax({}).done(function () {
//populate the select
//then at the last call the callback method which will set the value
callback()
})
};

get ID of clicked control

Using jQuery I'm trying to get the id of control, which I clicked (radiobutton). I read this question and tried almost everything from there:
alert($(this).get(0).id);
alert($(this).id);
alert($(this).attr('id'));
alert(this.id);
But I'm always getting: Undefined
I just don't understand what I'm doing wrong.
UPDATED:
Radiobuttons is generated dynamically in code behind by C#:
controlToReturn = new RadioButton
{
ID = controlId
};
((RadioButton)controlToReturn).Text = text;
((RadioButton)controlToReturn).Checked = Convert.ToBoolean(Convert.ToInt32(value));
((RadioButton)controlToReturn).GroupName = groupName;
((RadioButton)controlToReturn).CssClass = cssClass;
((RadioButton)controlToReturn).Attributes.Add("runat", "server");
((RadioButton)controlToReturn).Attributes.Add("onclick", "Show();");
and function in ASPX:
<script type="text/javascript" language="javascript">
function Show() {
if ($(this).cheked = true) {
console.log(this);
alert($(this).get(0).id);
alert($(this).id);
alert($(this).attr('id'));
alert(this.id);
}
}
</script>
I know radiobutton has id, I checked generated HTML.
Your problem is this has no context within your function and is in fact the window itself.
You would need to modify both the output html to provide context as an argument:
((RadioButton)controlToReturn).Attributes.Add("onclick", "Show(this);");
and change the function Show:
function Show(el) {
/* for jQuery use $(el) */
if(el.checked) {
alert(el.id);
}
}
C#:
((RadioButton)controlToReturn).Attributes.Add("onclick", "Show(this);");
JavaScript:
function Show(radio) {
if (radio.checked) {
alert(radio.id);
}
}
To attach a click-listener and alert the ID, your code would look something like this:
​$(function () {
$("input[type='radio']").on("click", function () {
alert(this.id);
});
});​
A working demo: http://jsfiddle.net/SSBnV/1/

jQuery highlighting with ASP:UpdatePanel

I'm currently working with the AJAX:UpdatePanelAnimationExtender and I've implemented it in code behind which is currently working perfectly but I've ran into a problem with using the UpdatePanelAnimationExtender and an ASP:Repeater. I've been messing around with different ways of implementing it but nothing has worked correctly...
I've tried to have it written in codebehind - inside itemBound (generates the code perfectly, is attached to the UPAE but of course is dropped on partial postback).
I've also attempted using it in the aspx which also posed a problem.
The repeater itself is creating a table of items (a cart) and I am attempting to highlight items that have changed when a postback happens (highlight qty if the qty changes, etc).
I've read that jquery has a much cleaner way of doing this and am attempting to go that direction.
edit:
I'm currently looking at
function pageLoad()
{
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
changedHighlight();
}
function EndRequestHandler(sender, args){
if (args.get_error() == undefined){ changedHighlight(); }
}
function changedHighlight() {
$(document).ready(function() {
$('span,input,option,select').live('change', function() { $(this).effect("highlight", {color: "#44EE22"}, 1500); });
});
}
I'd have to compare a stored value for it to the new posted value, which I'm working on right now. Also 'change' doesn't appear to work on asp:labels?
Ended up using a global var (eh..) due to the issue of postback with the UpdatePanel and DOM recreation every time (meaning not able to use $.data() or this.data()).
Will only highlight non-submit inputs and DOM elements that have an ID. (otherwise static asp:labels will continue to flash)
var oldVar = [];
function pageLoad()
{
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler)
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
}
function BeginRequestHandler(sender, args) {
$(document).ready(function() {
oldVar = [];
$('input,select,span').each(function() {
if (this.type != "submit" && this.id != '') oldVar[this.id] = getValue(this);
});
});
}
function EndRequestHandler(sender, args){
$(document).ready(function() {
$('input,select,span').each(function() {
if (this.type != "submit" && this.id != '')
{
if (oldVar[this.id] != getValue(this))
{
$(this).effect('highlight', {color: '#44EE22'}, 3000);
oldVar[this.id] = getValue(this);
}
}
});
});
}
function getValue(control){
if ('value' in control) return control.value;
else if('textContent' in control) return control.textContent;
else if('innerText' in control) return control.innerText;
}

Categories

Resources