I noticed that some validation tools use the "class" attribute to pass options to validation scripts.
Example:
<input class="input-field validate[required, email]" name="" type="text" />
the "required" and "email" would be picked up by the script as setting options.
I was wondering is there an easy way to achieve this or maybe this is already available in jQuery?
I want to use this as a means of passing certain settings to my script.
Any help would be appreciated,
Thanks
Edit:
Thanks #loseb your example works great.
Another thing I am trying to achieve by doing some small modification to your example:
function classAttributes( classString, className ) {
var data;
var regex = new RegExp(className+"\[(.*?)\]");
var matches = classString.match(regex);
if ( matches ) {
//matches[1] refers to options inside [] "required, email, ..."
var spec = matches[1].split(/,\s*/);
if ( spec.length > 0 ) {
data = spec;
}
}
return data;
}
any idea why "new RegExp(className+"[(.*?)]");" doesnt work. var matches is blank.
Edit:
second part of the question moved to:
javascript regex pattern with a variable string not working
If I understand you correctly this is the solution:
var className = $('.input-field').att('class');
var regex = /validate\[(.*?)\]/;
var matches = className.match(regex);
if (matches) {
//matches[1] refers to "required, email" string
var spec = matches[1].split(/,\s*/);
if (spec.length == 2) {
var attribute = spec[0]; //required or optional or anything else
var validator = spec[1]; //actual validation type
}
}
I would just use data to do this instead:
var mydata={required: true,email:false};
$('.input-field').data('validate',mydata);
see an example here:http://jsfiddle.net/MarkSchultheiss/FzaA8/
Related
I want the string 'Surveillance Capitalism' to be inputted letter by letter into a text input (or something that looks like one) as a user types.
The code works up to the point I try to add the letter into the input, at which point I am told 'Failed prop type: You provided a value prop to a form field without an onChange handler'. Is this method possible? If not what is a good alternative?
Html:
<input
id="search-bar"
type="text"
onKeyPress={this.handleKeyPress}
/>
JS:
//Dictates what is typed in the search bar
(https://stackoverflow.com/questions/27827234/how-to-handle-the-onkeypress-event-in-reactjs)
handleKeyPress = event => {
var firstSearchString = "Surveillance Capitalism";
//Converts firstSearchString into an array of its members (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)
var searchStringArray = Array.from(firstSearchString);
//Gets contents of search bar
var searchBar = document.getElementById("search-bar").value;
//Length of that content
var i = searchBar.length;
searchBar.value += searchStringArray[i];
};
Essentially I want to trick the user into thinking they can search whatever they want but when they go to type, my preset query will be entered letter by letter.
The problem is that you are assigning a variable to the search bar:
var searchBar = document.getElementById("search-bar").value;
then altering the variable, to fix your problem i just did this:
handleKeyPress = event => {
var firstSearchString = "Surveillance Capitalism";
var searchStringArray = Array.from(firstSearchString);
for(let i = 0; i < searchStringArray.length; i++) {
document.getElementById("search-bar").value += searchStringArray[i];
}
};
I think that's what you were having trouble with but i'm not sure if i understood the question. I hope this helped
Try the onChange event handler, rather than the onKeyPress handler. That should remove the error you have. They are functionally slightly different, but should accomplish the same thing.
I have to change my project form XML to JavaScript (at least some parts of it).
So I had construction like this :
$xml = simplexml_load_file("http://...);
$profile = $xml->profile;
$user_id = $profile->user_id;
Now I wanted to translate this into JavaScript so I used :
var xmlHttp_subscribe = new XMLHttpRequest();
xmlHttp_subscribe.onreadystatechange=postCall;
xmlHttp_subscribe.open("GET","http://...",true);
xmlHttp_subscribe.send();
and now function postCall()
function postCall(){
var t = document.getElementsByName("MY_API").value;
alert('t'+t);
var p = document.getElementsByName("profile").value;
alert('p'+p);
var h = document.getElementsByName("user_id").value;
//...//
}
The XML is under my http:// is like that :
<MY_API>
<profile>
<user_id>the_user_id</user_id>
</profile>
</MY_API>
What I would like to do is to get this 'the_user_id' part as string in plain text.
Does any one have any idea how to do this?
Am I looking in the good direction?
Thanks for any kind of help.
There is no function "getElementsByName". What you need is getElementsByTagName.
Check this link out, it should be what you're looking for
As suggested by Pineda, the right function name is getElementsByTagName, and in addition the right property name is not "value" but nodeValue, so you should use
function postCall(){
var h = document.getElementsByTagName("user_id").nodeValue;
}
I've got another difficult problem to solve with JavaScript. The string variable comes from outside form input value as you can see below
document.addEventListener('DOMContentLoaded', function() {
var Country = document.getElementById('countr').value;
}, false);
The string address which I need to change is a part of relative href address and will take two different forms.
models/world/some_site.html
or
models/local/some_site.html
The variable Country will be changing as well for example: German, England, France etc.
If I want to replace 'world' or 'local' with Country variable what I need to do is doing something like that
var address = address.split('world').join(Country).split('local').join(Country);
or
var address = address.replace('world', new RegExp(Country, 'g')).replace('local', new RegExp(Country, 'g'));
The result should be look for example like that
models/German/some_site.html
But it doesn't work I don't know why. Any help will be very precious for me.
I discovered that my Country variable don't want to be processed, why?
This script not display my variable at all.
document.addEventListener('DOMContentLoaded', function() {
var Country = document.getElementById('cotr').value;
}, false);
document.write(Country);
So this example don't working as well
address.replace(/(local|world)/,Country)
Any help?
My real code looks as below
Indeks.prototype.wyswietl = function(adres)
{
if (typeof adres == 'undefined') adres =
document.forms[this.id].elements['hasla'].value;
if (typeof this.ramka == 'string')
{
var okno =
window.open(adres, this.ramka, 'menubar=yes,toolbar=yes,location=yes,directories=no,status=yes,scrollbars=yes,resizable=yes');
if (okno) okno.focus();
else window.location.href = adres;
}
else this.ramka.location.href =
adres.replace(/(world|local)/,Country);//here I need replacement adres is address
}
First of all, join() is used for arrays and leaves commas in the resulting string, so you should use concat() instead. Second, replace() would be a much simpler solution, like so:
var regex = /(world|local)/;
address.replace(regex,Country);
EDIT:
I've tested my code, so the method itself works. The problem in that case must be in your Country variable. Are you sure its scope is global? The way it appears in that of yours function suggests it isn't visible anywhere outside the event listener. Or perhaps you can link the event listener directly to the rest of your code and pass it as a function argument if you consider globals to be evil.
you want to replace the middlepart of text models/local/some_site.html with Counry variable.
you can use split() function to split the string based on /.
after getting the splitted strings you can take index[1] value as it contains country value local or world to be replaced.
and then you can use replace() function for replacing the text.
Sample Code as below:
<script language="javascript">
var address="models/local/some_site.html";
var Country="france";//Example
var finaladdress=address.replace(address.split("/")[1],Country);
</script>
Complete Solution :
Code1: Declare your Country variable as global
var Country;//declare the Country outside the function so it becomes global
document.addEventListener('DOMContentLoaded', function() {
Country = document.getElementById('countr').value;
}, false);
Code2: Do replacement here
Indeks.prototype.wyswietl = function(adres)
{
if (typeof adres == 'undefined') adres =
document.forms[this.id].elements['hasla'].value;
if (typeof this.ramka == 'string')
{
var okno =
window.open(adres, this.ramka, 'menubar=yes,toolbar=yes,location=yes,directories=no,status=yes,scrollbars=yes,resizable=yes');
if (okno) okno.focus();
else window.location.href = adres;
}
else this.ramka.location.href =
adres.replace(adres.split("/")[1]),document.getElementById('countr').value); // here I need replacement
}
I have an issue related to converting html inputs names to a javascript object.
For example I have an input:
<input type="checkbox" name="product[1]">
<input type="checkbox" name="product[2]">
and I have javascript code:
var data = {};
$('input').each(function(){
// need to do something like
data[$(this).attr('name')] = $(this).attr('checked');
})
I expect to get data object like this;
data = {
product: {
1: 'checked',
2: 'checked'
}
}
Is this possible without using regular expressions?
Replacing your variables with literal values, you get this:
data["product[1]"] = true;
The square brackets have no meaning as they are inside a string, so you won't get any result.
There are ways around this. You could use eval: eval("data."+this.name+" = "+(this.checked?"true":"false"));
However since eval is best avoided, try this:
var m = this.name.match(/(.*)\[(\d+)\]/);
data[m[0]][m[1]] = this.checked;
Yes in general it is possible. You can do the following:
var noregexp = $(this).attr('name').split("[");
if (noregexp.length==2) {
//should be
var the_name = noregexp[0];
var the_index = noregexp[1].substr(0,noregexp[1].length-1); //this will get the index with removed ]
}
I made this up from my mind. It's not a beautiful solution but one without regexp as you wished.
You can get a data structure the way you need using:
var data = {product: []};
$('input').each(function(){
data.product[$(this).attr('name').match(/product\[([\d]*)\]/)[1]] = $(this).prop('checked');
})
console.log(data);
Check thid demo
I'm looking for a way using jquery/javascript to get a class name when I only know part of it and there are more than one classes applied to that element.
So if I'm looking for a class that I know starts with "charLimit_" I want to know that full class name even when it's not the only class applied to a given element.
Example HTML would be.
<input class="charLimit_30 lastNameValidation" type="text" />
What I have so far below will put both "charLimit_30" and "lastNameValidation" into an array, but how do I then say I only want "charLimit_30" and then only tell me the value found after the underscore (30).
var classMName = $('[class*=charLimit_]').attr("class").split(' ');
Thanks in advance for you help!!!
This is kinda like what inkedmn said, but in a more jQuery-ish way:
var numbersAfterCharLimit = [];
$('[class*="charLimit_"]').each(function() {
var matches;
if (matches = this.className.match(/(?:\s+|^)charLimit_([0-9]+)(?:\s+|$)/)) {
numbersAfterCharLimit.push(parseInt(matches[1], 10));
}
});
If you only need first occurrence and everything that follows underscore in class is a number, then something like this would do it:
$('[class*=charLimit_]').attr("class").match(/(?:\s|^)charLimit_(\d+)/)[1];
This appears to work (at least on stackoverflow):
var test = $('[class*=owner]').attr('class').split(' ');
for(i in test){
if(test[i].indexOf('post-sign') !== false){
test = test[i].split('-');
// replace this with a return
console.log(test[1]);
break;
}
}
And one that will work with the code that he is trying to do it with:
var test = $('[class*=charLimit_]').attr('class').split(' ');
for(i in test){
if(test[i].indexOf('charLimit_') !== false){
test = test[i].split('_');
// replace this with a return if it is in a function
console.log(test[1]);
break;
}
}
var classes = $('input').attr('class');
var myNum = '';
for(var i=0;i<classes.length;i++){
if(classes[i].match(/^charLimit_.*$/){
myNum = classes[i].split('_')[1];
}
}
Something like that would work, unless of course there's some jQuery magic way of doing it that I'm simply unaware of :)