Check for duplicate name before adding in the dropdown - javascript

I have two issues:
I want user to add the values in the dropdown but before that I am checking if the value is already present in that using this function:
function IsNameAlreadyPresent(List,Name){
$.each($("'#'+List option"),function(i,e){
if(e.innerHTML == Name){
return true;
}
});
}
function AddOptionName() {
var Name = $("#txtName").val();
if(IsNameAlreadyPresent(List,Name)) {
alert("Name \"" + Name + "\" already exists. \nPlease type an unique name.")
}
else{
AddNewOption(Name);
}
}
I want to use this same function many times in my code to check whether the value entered is unique or not by passing the id of the dropdown and the name to be entered. but somehow this doesnt work.
how to pass the id as a parameter ($("'#'+List option")?
I am using the same function to edit the text of the option as well. but somehow if the user clicks edit and he doesnt want to change the text and clicks OK it gives an alert that the option is already present.
The option is only once including the one open in the popup. how to check this ?
var x = document.getElementById("List");
var l_sName = x.options[x.selectedIndex].text;
$("#List option[value="+l_sName+"]").remove();

Your selector is wrong, it should be $("#"+List+" option"). Also return inside $.each() will not return from your function, but break $.each() if false. Change your IsNameAlreadyPresent(List,Name) to this:
function IsNameAlreadyPresent(List, Name) {
var result = false;
$.each($("#"+List+" option"), function (i, e) {
if (e.innerHTML == Name) {
result = true;
return false;
}
});
return result;
}
For this part you can add a name to be excluded for checking, for example:
function IsNameAlreadyPresent(List, Name, Excluded) {
var result = false;
$.each($("#"+List+" option"), function (i, e) {
if (e.innerHTML == Name && e.innerHTML != Excluded) {
result = true;
return false;
}
});
return result;
}
function AddOptionName(Excluded = "") {
var Name = $("#txtName").val();
if (IsNameAlreadyPresent(List, Name, Excluded)) {
alert("Name \"" + Name + "\" already exists. \nPlease type an unique name.")
} else {
AddNewOption(Name);
}
}
and then call it with AddOptionName( $("#"+List+" option:selected").html() );

Related

when the function works the else statement is the one that executed

Please Guys some Help Really i stuck here why the else statement works rather than if statement
function add() {
if (input.value !== "") {
localStorage.setItem("name", input.value);
results.innerHTML = `localStorage item <span class='green'>${input.value}</span> been added`;
input.value = '';
}
};
when the add() function add a value from the input i want to check if this value exists in the
localStorage but the else statement that is the one that works
function check() {
if (input.value !== "") {
if (localStorage.getItem(input.value)) {
results.innerHTML = `Found item in Local Storage With Name ${input.value}`;
} else {
results.innerHTML = `No Local Storage with Name <span class='green'>${input.value}</span>`;
}
}
}
You need to get the item by its name. localStorage.getItem(input.value) should be localStorage.getItem("name")

jQuery check multiple CSV lists

To simplify my problem i rewrote the code without the parsing of CSV, but instead with a variable that holds the data.
--CODE EDIT---
$(document).ready(function() {
var qID = 'xxx';
var source = ['text1', 'text2', 'etc3'];
var source2 = ['text4', 'text5', 'etc6'];
$('#question' + qID + ' input[type="text"]').change(function() {
var validVal = 0;
var inputVal = $(this).val();
// Loop through the text and test the input value
$(source).each(function(i) {
if (inputVal == this) { // If a match is found...
validVal = 1;
}
});
// If a valid text was entered
if (validVal == 1) { // A valid input
alert("GOOD");
} else { // An invalid input
alert("NOT GOOD");
}
var validVal2 = 0;
var inputVal2 = $(this).val();
$(source2).each(function(j) {
if (inputVal2 == this) { // If a match is found...
validVal2 = 1;
}
});
// If a valid text was entered
if (validVal2 == 1) { // A valid input
alert("GOOD2");
} else { // An invalid input
alert("NOT GOOD2");
}
});
});
The script works fine for one source (var source) but i want to check in the same text field 2 variables (source, source2) that will produce different alerts.
The script is run through a limesurvey form and the input is a simple [type="text"] field.
How do I check for 2 different arrays of text in the same text field?
Whenever you find yourself putting counters on variable names to create a series, you need to stop and think about what you are actually doing there. Making counted variable names is always wrong.
Use arrays.
var qID = 'xxx';
var source = [];
source.push(['text1', 'text2', 'etc']);
source.push(['text1', 'text2', 'etc44']);
source.push(['text15', 'text25', 'etc454']);
$('#question' + qID + ' input[type="text"]').change(function() {
var valid = false;
var inputVal = $(this).val();
$.each(source, function(i, terms) {
$.each(terms, function(i, term) {
valid = inputVal === term;
return !valid; // returning false stops the .each() loop
});
return !valid;
});
if (valid) {
alert("GOOD");
} else {
alert("NOT GOOD");
}
});
A more appealing way to express the nested loop above uses built-in methods of Array.
var valid = source.some(function (terms) {
return terms.includes(inputVal);
});
in ES6 syntax this can be made a one-liner:
var valid = source.some(terms => terms.includes(inputVal));

jQuery - Checking val isn't empty and contains a specific piece of text

So I've got a .js file that checks that the values of my form. I'm trying to check that the form values aren't empty, and that one of the values contains a specific piece of text (in this case, my name). If the form does hold my name, then run the rest of the script.
Where I have commented //etc etc, an AJAX script is ran that posts to a PHP file.
This is all functioning as expected, until I run the additional if statement checking the input value for my name.
$('#submit').click(function(e){
this.enabled=true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === ""){
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
if($('#name').val().indexOf("Rich") != -1){ // without this if statement, the code runs fine.
$('#message').html("You have entered the wrong name.");
return false;
}
} else {
if($('#name, #topic_title').length && $('#name, #topic_title').val().length){
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}}
// etc etc
});
Question: How would I go about checking that the value of the id '#name' isn't empty, and that it contains a specific piece of text?
Thanks in advance,
Richie.
Solution:
I removed the additional if statement and included the following code.
var name = $('#name').val();
if ( name.indexOf("Rich") || $.trim($("#name").val()) === ""){
If you indent your code consistently, it's fairly clear why you have a problem:
$('#submit').click(function(e) {
this.enabled = true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "") {
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
if ($('#name').val().indexOf("Rich") != -1) { // Note that this is WITHIN the `if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "")` condition
$('#message').html("You have entered the wrong name.");
return false;
}
} else {
if ($('#name, #topic_title').length && $('#name, #topic_title').val().length) {
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}
}
// etc etc
});
If you want it to be handled, it needs to be an else if for that condition instead:
$('#submit').click(function(e) {
this.enabled = true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "") {
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
} else if ($('#name').val().indexOf("Rich") != -1) { // without this if statement, the code runs fine.
$('#message').html("You have entered the wrong name.");
return false;
} else {
if ($('#name, #topic_title').length && $('#name, #topic_title').val().length) {
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}
}
// etc etc
});
(Well, as you have return, those could both just be if rather than else if...)
There are other problems though, for instance this expression in your final block:
$('#name, #topic_title').length
...which checks to see if either #name or #topic_title elements exist in your DOM at all (it doesn't do anything to check their values, and it doesn't require that they both exist, just one of them), and this:
$('#name, #topic_title').val().length
...will only check the value in #name, it will completely ignore the value in #topic_title, because when used as a getter, val only gets the value of the first element in the jQuery set. (Almost all of jQuery's functions that can be getters or setters are like that; the exception is text which is different from the others.)
Finally, this line:
this.enabled = true;
...is almost certainly a no-op, since the button cannot be clicked if it's not enabled, and as lshettyl points out, the property's name is disabled, not enabled. So this.disabled = false; if you're trying to enable it, or this.disabled = true; if you're trying to disable it.
By the look of your code, I assume you have a form that has either a class or an ID (or nothing). It'd be clever to use the form's submit event as opposed to click event of the submit button. This way you ensure that the form can also be submitted via the enter button (remember accessibility?). This is only an extension to T.J. Crowder's answer which has lots of good points from which you can learn/improve coding.
//Let's say your form has an ID 'topic'
$("#topic").on("submit", function() {
//Cache jQuery objects that would be resued, for better performance.
var $name = $("#name"),
$title = $("#topic_title"),
$msg = $('#message');
//One of the elements doesn't exist (exit)
//1 + 1 <= 1
if ($name.length + $title.length <= 1) {
return;
}
if ($.trim($name.val()) === "" || $.trim($title.val()) === "") {
$msg.html('you did not fill out one of the fields').css("color", "#be4343")
return;
} else if ($name.val().indexOf("Rich") !== -1) {
$msg.html("You have entered the wrong name.");
return;
} else {
//You do not need further checks such as length, val etc.
//as they have already been checked above.
var name = $name.val();
var topic_title = $title.val();
}
});
You can make comparison to know if it's empty:
if($('#name, #topic_title').length && $('#name, #topic_title').val().length){
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}}
if(name=='' || name==undefined){
//do stuff here
}
});

how to use contains functions with array in jquery?

i have an array which contains some values. i want if the textbox's value contains a value from any of the element of that array it will show alert "exists", otherwise "doesn't exists"
I have tried the following code:
$('[id$=txt_Email]').live('blur', function (e) {
var email = $('[id$=txt_Email]').val();
var array = ['gmail.com', 'yahoo.com'];
if (array.indexOf(email) < 0) { // doesn't exist
// do something
alert('doesnot exists');
}
else { // does exist
// do something else
alert('exists');
}
});
But this is comparing the whole value with the array's element. i want to use contains function as we can in C# with string.Please help me.
I want if user type "test#gmail.com" it will show exists in array. if user enter "test#test.com" it will alert doesnot exists.
I think you want
$.each(array, function () {
found = this.indexOf(email);
});
To find the match not exact string you need to do some thing like
Live Demo
arr = ['gmail.com', 'yahoo.com'];
alert(FindMatch(arr, 'gmail.co'));
function FindMatch(array, strToFind)
{
for(i=0; i < array.length; i++)
{
if(array[i].indexOf( strToFind) != -1)
return true;
}
return false;
}
​
$(document).on('blur', '[id$=txt_Email]', function (e) {
var email = this.value, array = ['gmail.com', 'yahoo.com'];
if (email.indexOf('#')!=-1) {
if ($.inArray(email.split('#')[1], array)!=-1) {
alert('exists');
}else{
alert('does not exists');
}
}
});​
FIDDLE
b is the value, a is the array
It returns true or false
function(a,b){return!!~a.indexOf(b)}

How to get a SharePoint-UserField with JavaScript?

Hallo,
i need to write some javascript that gets the contents of a userfield in a sharepoint-website. I can get most fields with the javascript-function 'getTagFromIdentifierAndTitle' of Using Javascript to Manipulate a List Form Field, but not UserFields.
So how can i get UserFields?
Thanks!
I traced how address book interacts with user field. To get values it uses function getUplevel(ctx) and to set values can be used function EntityEditorCallback(xml, ctx). First function will return html/xml mixed string with user information. Second function input must be special formatted xml string.
// Get values
var ctx='ctl00_m_g_e5a1501a_..._ctl04_ctl00_ctl00_UserField';
var values=getUplevel(ctx);
alert(values);
// Set values
var xml='<Entities Append="False" Error="" Separator=";" MaxHeight="3">'+
'<Entity Key="DOMAIN\\loginname" DisplayText="Display Name" IsResolved="True" Description="DOMAIN\\loginname">'+
'<ExtraData>'+
'<ArrayOfDictionaryEntry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">'+
'<DictionaryEntry><Key xsi:type="xsd:string">DisplayName</Key><Value xsi:type="xsd:string">Display Name</Value></DictionaryEntry>'+
'<DictionaryEntry><Key xsi:type="xsd:string">Email</Key><Value xsi:type="xsd:string">Display.Name#domain.ee</Value></DictionaryEntry>'+
'<DictionaryEntry><Key xsi:type="xsd:string">SPUserID</Key><Value xsi:type="xsd:string">1</Value></DictionaryEntry>'+
'<DictionaryEntry><Key xsi:type="xsd:string">PrincipalType</Key><Value xsi:type="xsd:string">User</Value></DictionaryEntry>'+
'</ArrayOfDictionaryEntry>'+
'</ExtraData>'+
'<MultipleMatches />'+
'</Entity>'+
'</Entities>';
EntityEditorCallback(xml,ctx);
Tricky part is ctx attribute that must be target field id. In user field html there is no title attribute, so to find right element by display name with js is very complex. I suggest to pass field id to the javascript from server side. For example you can create custom WebPart where you write to the page field id-s from collection SPContext.Current.FormContext.FieldControlCollection.
Here is the custom code that I put together. It relies on the exact HTML that SharePoint uses for the PeoplePicker. It does work on both IE and Firefox. For the columnName parameter, pass the "public" name of the column, not the internal name.
function getParentElementByTagName(baseNode, tagName)
{
var currNode;
if(baseNode !== null)
{
currNode = baseNode.parentNode;
while((currNode !== null) && (currNode.nodeName != tagName))
{
currNode = currNode.parentNode;
}
return currNode;
}
else
{
return null;
}
}
function getPeoplePickerCell(columnName)
{
var search = 'FieldName="' + columnName + '"';
var nodes = document.getElementsByTagName("TEXTAREA");
for(var i=0; i < nodes.length; i++)
{
if(nodes[i].title == "People Picker")
{
var outerCell = getParentElementByTagName(nodes[i], "SPAN").parentNode.parentNode;
if(outerCell.innerHTML.indexOf(search) > 0)
{
return nodes[i].parentNode;
}
}
}
return null;
}
function getSPPeoplePicker(columnName, value)
{
var cell = getPeoplePickerCell(columnName);
if(cell !== null)
{
return cell.childNodes[0].innerHTML;
}
else
{
return null;
}
}
function setSPPeoplePicker(columnName, value)
{
var cell = getPeoplePickerCell(columnName);
if(cell !== null)
{
cell.childNodes[0].innerHTML = value;
cell.childNodes[1].value = value;
}
}
function disableSPPeoplePicker(columnName)
{
var cell = getPeoplePickerCell(columnName);
if(cell !== null)
{
disableElement(cell.childNodes[0]);
disableElement(cell.childNodes[1]);
}
}
function enableSPPeoplePicker(columnName)
{
var cell = getPeoplePickerCell(columnName);
if(cell !== null)
{
enableElement(cell.childNodes[0]);
enableElement(cell.childNodes[1]);
}
}

Categories

Resources