For my Project I need to have a site, which can generate a custom amount of Inputs, which will become buttons in another page.
And I need the values for the Input in order to Label the Buttons correctly.
HTML
<h2>settings:</h2>
<p>Add Amount of Checks:</p>
<input id="NumOfButtons"
name="NumOfButtons"
pattern=""
size="30"
spellcheck="false"
title="Amount of Checks"
value="">
<script>
let input = document.getElementById("NumOfButtons");
let listTA = new Array;
input.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
event.preventDefault();
var x = parseInt(document.getElementById("NumOfButtons").value);
listTA = new Array(x);
for (let i = 0; i < x; ++i) {
var textarea = document.createElement("input");
textarea.name = "input";
textarea.maxLength = "100";
textarea.id = "TextAreaID"
listTA[i] = textarea;
document.getElementById("Buttons").appendChild(textarea);
}
}
});
</script>
<div id="Buttons">
<br />
<button onclick="sendDataAndGoToKontrolle()">save & continue</button>
<p>Reset F5</p>
</div>
<script>
function sendDataAndGoToKontrolle() {
var filtered;
if (listTA != null) {
let x = new Array;
for (let i = 0; i < listTA.length; ++i) x[i] = listTA[i].document.getElementById("TextAreaID").value;
if (!(x.length === 0)) {
for (let i = 0; i < x.length; ++i) {
if (x[i] === null) {
var filtered = x.filter(function (el) { return el != null; });
console.log("TextAreas filtered!")
} else console.log("Nothing to filter!")
}
} else console.log("Nothin written in TextAreas!");
} else console.log("No TextArea created!");
if (!(filtered === null)) {
//Send Prüfungen to Controller
$.ajax({
url: "#Url.Action("NewIDSettingsPage")",
type: "GET",
data: { Prüfungen: filtered },
success: function () {
console.log("Successfully sent!");
//window.location.href = '/home/NewIDSettingsPage';
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText;
console.log("ERROR: " + errorMessage);}});
} else console.log("ERROR");
}
</script>
The result should be a list/Array of string(values of the Inputs).
If you need any further information, please write a Comment and I will look to reply quickly.
Do not give all the input elements the same id. textarea.id = "TextAreaID" is wrong.
If you want to group the inputs together you should set the class:
textarea.className = "TextAreaClass"
Or if you want to give each one an id, append i to the id to make it unique:
textarea.id = "TextAreaID"+i;
When trying to get the values of your inputs you have the following:
x[i] = listTA[i].document.getElementById("TextAreaID").value;
Which doesn't make a lot of sense. What you should probably be doing is:
x[i] = listTA[i].value;
Because you have stored the element in the array, you don't need to get the element from the document.
In my application i want display the suggestion names based on the character that user types in that input box. I get the user input using keyup event and i have a array of names from that i want to select the names that matches with the user input only from the starting letters. For Example if the user types A the suggestion show the name start with A,(For Ro-Root Valuation) How to do this?
$( document ).ready(function() {
var usernames = ["Abisi","Bentaven", "Root Valuation", "Leidos Health", "Visante", "vendor1", "yest1", "example"];
var displayname = [];
$('#input-text').keyup(function(event){
var $textValue = $(this).val();
jQuery.each( usernames,function( i, val ) {
*** find that matching name ***
if($textValue == val){
displayname.push(val);
}
});
});
You can try something like this:
JSFIDDLE: http://jsfiddle.net/bqkobo79/1/
var length= $textValue.length;
displayname=jQuery.grep(usernames, function( element, i ) {
if(element.toLowerCase().substr(0,length)===$textValue.toLowerCase())
return element;
});
You have to make sure that the text typed matches the name:
$textValue = $textValue.toLowerCase();
val = val.toLowerCase();
var is_matched = ($textValue.substr(0, ($textValue.length)) == val.substr(0, ($textValue.length)))
To make sure that you get suggestions you need to send after checking if it is true:
if (is_matched == true) {
displayname.push(val);
} else {
return false;
}
Final Code:
$( document ).ready(function() {
var usernames = ["Abisi","Bentaven", "Root Valuation", "Leidos Health", "Visante", "vendor1", "yest1", "example"];
var displayname = [];
$('#input-text').keyup(function (event) {
var $textValue = $(this).val();
jQuery.each(usernames, function (i, val) {
$textValue = $textValue.toLowerCase();
val = val.toLowerCase();
var is_matched = ($textValue.substr(0, ($textValue.length)) == val.substr(0, ($textValue.length)))
if (is_matched == true) {
displayname.push(val);
} else {
return false;
}
});
});
String.prototype.indexOf can tell you if a string contain another string and the index of the first match of that substring.
"Abisi".indexOf("A") == 0
In your case you can use it to retrieve a set of strings that start with the value of the text input
var usernames = ["Abisi","Bentaven", "Root Valuation", "Leidos Health", "Visante", "vendor1", "yest1", "example"];
var displayname = [];
$('#input-text').keyup(function(event){
var $textValue = $(this).val();
displayname = [];
if ($textValue.length > 0){
jQuery.each( usernames,function( i, val ) {
if(val.indexOf($textValue) === 0){
displayname.push(val);
}
});
}
console.log(displayname);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="input-text"/>
I have a select2 box, an I was to limit this to accept only email addresses.
I am trying to do this by writing a custom formatSelection function, as
formatSelection: function(object, container){
if(validateEmail(object.text)){
return object.text;
}
else{
return "";
}
}
I am expecting that returning an empty string would be enough to not show this input in select2, but I am getting an empty result.
As of select2 4.0 +, just use the createTag function:
createTag: function(term, data) {
var value = term.term;
if(validateEmail(value)) {
return {
id: value,
text: value
};
}
return null;
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\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,}))$/;
return re.test(email);
}
I have solved this. Just copy paste the code below and it will work smooth.
validate: function(value) {
if(value && value.length != 0){
var emailText = "";
var isValidEmail = true;
var isEmailLengthValid = true;
for (var i in value) {
var email = value[i];
isValidEmail = validateEmail(email);
if(isValidEmail == false){
break;
}else{
emailText = (i == 0) ? emailText : ", " + emailText;
if(emailText.length > 250){
isEmailLengthNotValid = false;
break;
}
}
}
if(isValidEmail == false){
return 'Enter a valid email address';
}else if(isEmailLengthValid == false){
return 'Maximum 250 characters allowed';
}
}
}
Also add below function validateEmail() which uses regex to validate email string.
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\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,}))$/;
return re.test(email);
}
it isn't clear from your question where your data source is. if the data source is from an ajax call then you can do server side validation and only return the email addresses.
but i suspect that you want to accept user input and only of valid email addresses. The Select2 docs explain the createSearchChoice function in the initialization $opts. you could insert your validateEmail function here and decide if you want to accept the new answer or not.
you might even want to write to an external DOM element any errors you find so the user knows they have to go back and correct the invalid email address.
//Allow manually entered text in drop down.
createSearchChoice: function(term, data) {
if ( $(data).filter( function() {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {id:term, text:term};
}
},
i use select2 4.01
regex validator email
function isEmail(myVar){
var regEmail = new RegExp('^[0-9a-z._-]+#{1}[0-9a-z.-]{2,}[.]{1}[a-z]{2,5}$','i');
return regEmail.test(myVar);
}
i return only a text without id in the return json if it's no valid. in this cas, you can add alert no selectable.
createTag: function (params)
{
if(!isEmail(params.term)){
return {
text: params.term,
};
}
return {
id: params.term,
text: params.term,
};
}
In your templateResult
function formatRepoReceiver (repo) {
if (repo.loading) return repo.text;
var markup = "";
if(typeof(repo.email) == 'undefined'){
// >>>your Alert<<<<
if(!isEmail(repo.text)){
if(repo.text == ''){
return null;
}
return 'Address email no valid';
}
//----------------------------
markup = "<div class='select2-result-repository clearfix'>"+
"<div class='select2-result-repository__meta'>" +
"<span>"+ repo.text +"</span> "+
"(<span>" + repo.text + "</span>)"+
"</div>"+
"</div";
}
else{
markup = "<div class='select2-result-repository clearfix'>"+
"<div class='select2-result-repository__meta'>" +
"<span>"+ repo.name +"</span> "+
"(<span>" + repo.email + "</span>)"+
"</div>"+
"</div";
}
return markup;
}
$('.select2-tokenizer').on('change', function() {
var num= this.value
if(!$.isNumeric(num)){
$('option:selected',this).remove();
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Please enter an integer!'
})
}
});
I've been banging my head over this.
Using jquery or javascript, how can I toggle variables & values and then rebuild the query string? For example, my starting URL is:
http://example.com?color=red&size=small,medium,large&shape=round
Then, if the user clicks a button labeled "red", I want to end up with:
http://example.com?size=small,medium,large&shape=round //color is removed
Then, if the user clicks "red" again, I want to end up with:
http://example.com?size=small,medium,large&shape=round&color=red //color is added back
Then, if the user clicks a button labeled "medium", I want to end up with:
http://example.com?size=small,large&shape=round&color=red //medium is removed from list
Then, if the user clicks the labeled "medium" again, I want to end up with:
http://example.com?size=small,large,medium&shape=round&color=red //medium added back
It doesn't really matter what order the variable are in; I've just been tacking them to the end.
function toggle(url, key, val) {
var out = [],
upd = '',
rm = "([&?])" + key + "=([^&]*?,)?" + val + "(,.*?)?(&.*?)?$",
ad = key + "=",
rmrplr = function(url, p1, p2, p3, p4) {
if (p2) {
if (p3) out.push(p1, key, '=', p2, p3.substr(1));
else out.push(p1, key, '=', p2.substr(0, p2.length - 1));
} else {
if (p3) out.push(p1, key, '=', p3.substr(1));
else out.push(p1);
}
if (p4) out.push(p4);
return out.join('').replace(/([&?])&/, '$1').replace(/[&?]$/, ''); //<!2
},
adrplr = function(s) {
return s + val + ',';
};
if ((upd = url.replace(new RegExp(rm), rmrplr)) != url) return upd;
if ((upd = url.replace(new RegExp(ad), adrplr)) != url) return upd;
return url + (/\?.+/.test(url) ? '&' : '?') + key + '=' + val; //<!1
}
params self described enough, hope this help.
!1: changed from ...? '&' : '' to ... ? '&' : '?'
!2: changed from .replace('?&','?')... to .replace(/([&?]&)/,'$1')...
http://jsfiddle.net/ycw7788/Abxj8/
I have written a function, which efficiently results in the expected behaviour, without use of any libraries or frameworks. A dynamic demo can be found at this fiddle: http://jsfiddle.net/w8D2G/1/
Documentation
Definitions:
The shown example values will be used at the Usage section, below
- Haystack - The string to search in (default = query string. e.g: ?size=small,medium)
- Needle - The key to search for. Example: size
- Value - The value to replace/add. Example: medium.
Usage (Example: input > output):
qs_replace(needle, value)
If value exists, remove: ?size=small,medium > ?size=small
If value not exists, add: ?size=small > size=small,medium
qs_replace(needle, options) Object options. Recognised options:
findString. Returns true if the value exists, false otherwise.
add, remove or toggleString. Add/remove the given value to/from needle. If remove is used, and the value was the only value, needle is also removed. A value won't be added if it already exists.
ignorecaseIgnore case while looking for the search terms (needle, add, remove or find).
separatorSpecify a separator to separate values of needle. Default to comma (,).
Note : A different value for String haystack can also be defined, by adding it as a first argument: qs_replace(haystack, needle, value) or qs_replace(haystack, needle, options)
Code (examples at bottom). Fiddle: http://jsfiddle.net/w8D2G/1/:
function qs_replace(haystack, needle, options) {
if(!haystack || !needle) return ""; // Without a haystack or needle.. Bye
else if(typeof needle == "object") {
options = needle;
needle = haystack;
haystack = location.search;
} else if(typeof options == "undefined") {
options = needle;
needle = haystack;
haystack = location.search;
}
if(typeof options == "string" && options != "") {
options = {remove: options};
var toggle = true;
} else if(typeof options != "object" || options === null) {
return haystack;
} else {
var toggle = !!options.toggle;
if (toggle) {
options.remove = options.toggle;
options.toggle = void 0;
}
}
var find = options.find,
add = options.add,
remove = options.remove || options.del, //declare remove
sep = options.sep || options.separator || ",", //Commas, by default
flags = (options.ignorecase ? "i" :"");
needle = encodeURIComponent(needle); //URL-encoding
var pattern = regexp_special_chars(needle);
pattern = "([?&])(" + pattern + ")(=|&|$)([^&]*)(&|$)";
pattern = new RegExp(pattern, flags);
var subquery_match = haystack.match(pattern);
var before = /\?/.test(haystack) ? "&" : "?"; //Use ? if not existent, otherwise &
var re_sep = regexp_special_chars(sep);
if (!add || find) { //add is not defined, or find is used
var original_remove = remove;
if (subquery_match) {
remove = encodeURIComponent(remove);
remove = regexp_special_chars(remove);
remove = "(^|" + re_sep + ")(" + remove + ")(" + re_sep + "|$)";
remove = new RegExp(remove, flags);
var fail = subquery_match[4].match(remove);
} else {
var fail = false;
}
if (!add && !fail && toggle) add = original_remove;
}
if(find) return !!subquery_match || fail;
if (add) { //add is a string, defined previously
add = encodeURIComponent(add);
if(subquery_match) {
var re_add = regexp_special_chars(add);
re_add = "(^|" + re_sep + ")(" + re_add + ")(?=" + re_sep + "|$)";
re_add = new RegExp(re_add, flags);
if (subquery_match && re_add.test(subquery_match[4])) {
return haystack;
}
if (subquery_match[3] != "=") {
subquery_match = "$1$2=" + add + "$4$5";
} else {
subquery_match = "$1$2=$4" + sep + add + "$5";
}
return haystack.replace(pattern, subquery_match);
} else {
return haystack + before + needle + "=" + add;
}
} else if(subquery_match){ // Remove part. We can only remove if a needle exist
if(subquery_match[3] != "="){
return haystack;
} else {
return haystack.replace(pattern, function(match, prefix, key, separator, value, trailing_sep){
// The whole match, example: &foo=bar,doo
// will be replaced by the return value of this function
var newValue = value.replace(remove, function(m, pre, bye, post){
return pre == sep && post == sep ? sep : pre == "?" ? "?" : "";
});
if(newValue) { //If the value has any content
return prefix + key + separator + newValue + trailing_sep;
} else {
return prefix == "?" ? "?" : trailing_sep; //No value, also remove needle
}
}); //End of haystack.replace
} //End of else if
} else {
return haystack;
}
// Convert string to RegExp-safe string
function regexp_special_chars(s){
return s.replace(/([[^$.|?*+(){}\\])/g, '\\$1');
}
}
Examples (Fiddle: http://jsfiddle.net/w8D2G/1/):
qs_replace('color', 'red'); //Toggle color=red
qs_replace('size', {add: 'medium'}); //Add `medium` if not exist to size
var starting_url = 'http://example.com?color=red&size=small,medium,large&shape=round'
starting_url = qs_replace(starting_url, 'color', 'red'); //Toggle red, thus remove
starting_url = qs_replace(starting_url, 'color', 'red'); //Toggle red, so add it
alert(starting_url);
This is the solution for your task: http://jsfiddle.net/mikhailov/QpjZ3/12/
var url = 'http://example.com?size=small,medium,large&shape=round';
var params = $.deparam.querystring(url);
var paramsResult = {};
var click1 = { size: 'small' };
var click2 = { size: 'xlarge' };
var click3 = { shape: 'round' };
var click4 = { shape: 'square' };
var clickNow = click4;
for (i in params) {
var clickKey = _.keys(clickNow)[0];
var clickVal = _.values(clickNow)[0];
if (i == clickKey) {
var ar = params[i].split(',');
if (_.include(ar, clickVal)) {
var newAr = _.difference(ar, [clickVal]);
} else {
var newAr = ar;
newAr.push(clickVal);
}
paramsResult[i] = newAr.join(',');
} else {
paramsResult[i] = params[i];
}
}
alert($.param(paramsResult)) // results see below
Init params string
{ size="small, medium,large", shape="round"} // size=small,medium,large&shape=round
Results
{ size="small"} => { size="medium,large", shape="round"} //size=medium%2Clarge&shape=round
{ size="xlarge"} => { size="small,medium,large,xlarge", shape="round"} // size=small%2Cmedium%2Clarge%2Cxlarge&shape=round
{ shape="round"} => { size="small,medium,large", shape=""} //size=small%2Cmedium%2Clarge&shape=
{ shape="square"} => { size="small,medium,large", shape="round,square"} //size=small%2Cmedium%2Clarge&shape=round%2Csquare
productOptions is the only thing you need to modify here to list all the available options and their default state. You only need to use the public API function toggleOption() to toggle an option.
(function(){
//Just keep an object with all the options with flags if they are enabled or disabled:
var productOptions = {
color: {
"red": true,
"blue": true,
"green": false
},
size: {
"small": true,
"medium": true,
"large": true
},
shape: {
"round": true
}
};
//After this constructing query becomes pretty simple even without framework functions:
function constructQuery(){
var key, opts, qs = [], enc = encodeURIComponent, opt,
optAr, i;
for( key in productOptions ) {
opts = productOptions[key];
optAr = [];
for( i in opts ) {
if( opts[i] ) {
optAr.push( i );
}
}
if( !optAr.length ) {
continue;
}
qs.push( enc( key ) + "=" + enc( optAr.join( "," ) ) );
}
return "?"+qs.join( "&" );
};
//To toggle a value and construct the new query, pass what you want to toggle to this function:
function toggleOption( optionType, option ) {
if( optionType in productOptions && option in productOptions[optionType] ) {
productOptions[optionType][option] = !productOptions[optionType][option];
}
return constructQuery();
}
window.toggleOption = toggleOption;
})()
Example use:
// "%2C" = url encoded version of ","
toggleOption(); //Default query returned:
"?color=red%2Cblue&size=small%2Cmedium%2Clarge&shape=round"
toggleOption( "color", "red" ); //Red color removed:
"?color=blue&size=small%2Cmedium%2Clarge&shape=round"
toggleOption( "color", "blue" ); //Blue color removed, no color options so color doesn't show up at all:
"?size=small%2Cmedium%2Clarge&shape=round"
toggleOption( "color", "blue" ); //Blue color enabled again:
"?color=blue&size=small%2Cmedium%2Clarge&shape=round"
toggleOption( "shape", "round" ); //The only shape option removed
"?color=blue&size=small%2Cmedium%2Clarge"
I have tried this and this may give the desire result
<script>
var url='http://example.com?color=red&size=small,medium,large&shape=round';
var mySplitResult = url.split("?");
var domain=mySplitResult[0];
var qstring=mySplitResult[1];
var proparr=new Array();
var valarr=new Array();
var mySplitArr = qstring.split("&");
for (i=0;i<mySplitArr.length;i++){
var temp = mySplitArr[i].split("=");
proparr[i]=temp[0];
valarr[i]=temp[1].split(",");
}
function toggle(property,value)
{
var index;
var yes=0;
for (i=0;i<proparr.length;i++){
if(proparr[i]==property)
index=i;
}
if(index==undefined){
proparr[i]=property;
index=i;
valarr[index]=new Array();
}
for (i=0;i<valarr[index].length;i++){
if(valarr[index][i]==value){
valarr[index].splice(i,1);
yes=1;
}
}
if(!yes)
{
valarr[index][i]=value;
}
var furl=domain +'?';
var test=new Array();
for(i=0;i<proparr.length;i++)
{
if(valarr[i].length)
{
test[i]=valarr[i].join(",");
furl +=proparr[i]+"="+test[i]+"&";
}
}
furl=furl.substr(0,furl.length-1)
alert(furl);
}
</script>
<div>
<input id="color" type="button" value="Toggle Red" onclick="toggle('color','red')"/>
<input id="shape" type="button" value="Toggle shape" onclick="toggle('shape','round')"/>
<input id="size" type="button" value="Toggle Small" onclick="toggle('size','small')"/>
<input id="size" type="button" value="Toggle large" onclick="toggle('size','large')"/>
<input id="size" type="button" value="Toggle medium" onclick="toggle('size','medium')"/>
<input id="size" type="button" value="Toggle new" onclick="toggle('new','yes')"/>
</div>