I have multiple form input elements. I would like to add a pattern attribute and a title attribute to each one, but rather than do so manually, I want to dynamically add the same pattern and title to each form input using JavaScript/jQuery.
This is what the form input fields look like now:
<input type="text" class="form-control" id="paycheck" />
<input type="text" class="form-control" id="investments" />
<input type="text" class="form-control" id="otherIncome" />
As an end result I would like each form input to look like the following:
<input pattern="\d*\.?\d*" title="blah blah blah" type="text" class="form-control" id="paycheck" />
etc...
As examples, I've tried the following for the pattern attribute, but none of them work:
$( "input" ).attr("pattern", '\d*\.?\d*');
$( "input" ).attr("pattern", \d*\.?\d* );
$( ".formClass input" ).attr("pattern", '\d*\.?\d*');
$( "input" ).prop("pattern", '\d*\.?\d*');
$( "input" ).prop("pattern", \d*\.?\d* );
$( ".formClass input" ).prop("pattern", '\d*\.?\d*');
...imagine something similar for the title attribute...
In the end, I found that the syntax was correct. There was an error somewhere else in the code preventing that statement from being run. Just goes to show that you should always make sure everything is good elsewhere in your code first.
However, I did learn a few things from this which I will note for others:
The jQuery .attr() function will dynamically add any attribute you specify, so you don't need to put pattern="" in your form elements first in order for the value to be added or changed.
Of important note, if you are going to dynamically add a regex using jQuery, YOU NEED TO ESCAPE certain characters.
The regex was originally \d*\.?\d* but in the DOM it was showing up as d*.?d* so when sending the regex through jQuery I escaped the backslashes like so: \\d*\\.?\\d*.
Finally, I did not have to make my fields required for the regex to work. The HMTL5 validation only threw an error for me if I included incorrect text in the field, and when it threw an error, the form was not submitted. If I left the fields empty or put correct text in the fields, then no error was thrown. I'm up for an explanation if I'm wrong.
Related
I have a search input tag that is being added by a jQuery plug-in:
<input type="search" />
Note that this does not have an ID, CLASS, or NAME. I need the search input tag to look like this:
<input type="search" name="myname" />
A simple solution is for me to update the jQuery plug-in. However, I do not want to do this as it will cause challenges when I upgrade this plug-in in the future.
This JavaScript works properly and adds the name attribute:
$(document).ready(function() {
document.getElementsByTagName("input")[0].setAttribute("name", "myname");
});
The problem is that the "[0]" in this function relies on the search input being the first input field in the form. I do not think this solution is sustainable.
There are other inputs in the form. This is the only one with the type attribute equal to "search." Is there a way to identify it by this attribute? Or, is there another solution you propose?
Thank you for your time!
You can use the document.querySelector:
document.querySelector("input[type='search']")
Below is an example (you can inspect the output to see name attribute):
document.querySelector("input[type=search]").setAttribute("name", "myname");
<input type="search" value="foo" />
<input type="bar" value="bar" />
You can target a selection by anything. So, the selector input[type="search"]' will work.
If you want to apply this to all input's of type search, this is good enough, and you get all of them in here:
$('input[type="search"]')
This works without jQuery too:
document.querySelectorAll('input[type="search"]')
A more targeted approach would be
document.querySelectorAll('div.filter input[type="search"]')
So I have javascript code to prepend "tag:" or "vendor:" before every search term, but I wanted to hide that from the user, so I created a hidden input field to send the code but it's not properly prepending the "tag:" and "vendor:" before every word. and instead inputs the entire string, then the search terms.
<form method="get" action="/search" id="search-home">
<button type="submit" value="search"></button>
<input type="hidden" name="type" value="product" />
<input type="hidden" name="q" class="searchtext" />
<input type="text" name="red" placeholder="Search"/>
</form>
<script>
$(document).on('submit','#search-home',function(){
var searchtext = $('.searchtext').val();
$('.searchtext').val("tag:"+searchtext+"* OR vendor:"+searchtext+"*");
});
</script>
Here's what the Url looks like with the code
http://zzz.co/search?type=product&q=tag%3A+OR+vendor%3A&red=tote#fullscreen=true&search=home
Here's what it's supposed to look like.
http://zzz.co/search?type=product&q=tag%3Atote+OR+vendor%3Atote#fullscreen=true&search=home
You're getting an empty value and inserting it here:
$(document).on('submit','#search-home',function(){
var searchtext = $('.searchtext').val(); // <- HERE
$('.searchtext').val("tag:"+searchtext+"* OR vendor:"+searchtext+"*");
});
What you should be doing is getting the user given query, which is the input you named "red".
$(document).on('submit','#search-home',function(){
var searchtext = $('input[name="red"]').val();
$('.searchtext').val("tag:"+searchtext+"* OR vendor:"+searchtext+"*");
});
With the above fix, your URL will look similar to:
http://zzz.co/search?type=product&q=q=tag%3Atote+OR+vendor%3Atote&red=tote.
I do not know where you're getting your hashbang(#) from, but I would assume it will append at the end as before.
If you want to get rid of the red=tote part, you have a few options. Emptying the value via $('input[name="red"]').val(''); will make it appear in your url as red=. If you want it gone entirely, you should use $('input[name="red"].remove();.
I would also advise having your "on" hook attached to the form, not the entire document. This is just a good practice to avoid using unnecessary resources as this hook will bubble every time a form is submitted, regardless of the selector. Instead, consider:
$('form#search-home').on('submit', 'button[type="submit"]', function() { ... };
That way it will only bubble when a submit event happens on that specific form, greatly reducing the possible instances those resources are used.
I guess this is pretty basic yet I don't know how to solve this puzzle. What I have is two inputs generated by a plugin in Wordpress. What I want to do is to change the placeholders in the fields.
The problem is that the fields ID (which I use to call the inputs via Javascript) is the same, resulting in that only the first inputs placeholder changes.
The auto-generated HTML:
<input type="password" placeholder="Lösenord" name="swpm-19" id="swpm-19" value="" class="swpm-text swpm-large required ">
<input type="password" placeholder="Retype password Here" name="swpm-19_re" id="swpm-19" value="" class="swpm-text swpm-large required ">
The Javascript:
<script type="text/javascript">
jQuery(document).ready(function($){
$('#swpm-19').attr("placeholder","Lösenord");
});
</script>
I have no idea how to call the second input since the ID's are the same. What I did notice is that the names of the inputs is different. The second inputs name is "swmp-19_re". Would it be possible to fetch the input in the Javascript via the name instead of the ID?
You cannot have duplicate id, this is invalid document.
You can use the attribute value selector to select the elements by using name attribute value.
$('input[name="swpm-19"], input[name="swpm-19_re"]').attr('placeholder', 'Lösenord');
You can also use starts with as
$('input[name^="swpm-19"]').attr('placeholder', 'Lösenord');
For more information on the type of CSS (attribute) selectors that jQuery supports check this page.
Considering the following HTML:
<form id="upvoteForm" method="post" action="/post/upvote">
<input type="text" name="post_id" id="post_id"/>
</form>
<form id="downvoteForm" method="post" action="/post/downvote">
<input type="text" name="post_id" id="post_id"/>
</form>
<input type="hidden" id="_postid" value="1"/>
I'm trying to set the two input fields with the name post_id to to value from _postid using this JavaScript and jQuery:
$(document).ready(function() {
$('#post_id').val($('#_postid').val());
});
However, as you can see in this jsFiddle, it's only setting the value of the first one. How do I set the value of both of them? I thought the selector would end up grabbing both.
Now, I realize you might be wondering why I have two forms on this page. The basic reason is I have button inputs that I've styled the way I want but then I use the onclick to call the submit of the appropriate form here. I am ultimately going to be leveraging AJAX here, but that's coming later.
id is always unique. you cannot select 2 elements with same id. select by name
$(document).ready(function() {
$('input[name=post_id]').val($('#_postid').val());
});
Having two HTML elements with the same ID is illegal and will cause undefined behavior such as what you're experiencing. Using the same name is valid, however. Therefore you could use a selector like $('form > input[name=post_id]'), which would look for an input inside of a form with the name attribute set to post_id.
Is it valid to replace elements with <element /> to <element></element>. In this case i want to have,
<input {attributes}></input>
just so i can append validation data within... Also could this be possible from a <br /> or <hr /> etc?
The <input> tag does not have a </input> and there is no need for one. Same for <br> and <hr>. You can put validation data as attributes on the input tag (or any tag) with custom attributes like this:
<input type="text" data-validate="num">
If what you mean by validation is separate HTML that you want to display near the input tag, then put it in it's own tags before or after the <input> tag:
<input type="text"><span class="validHint">This field accepts only numbers</span>
<input></input> is not valid in neither HTML4.01 nor HTML5.
According to W3C's validation service: (reason highlighted)
Validation Output: 1 Error
Line 9, Column 15: Stray end tag input.
<input></input>
So here you go, you can not replace <input> with <input></input>.
If you want to attach data to elements, why not use data-* attributes? (e.g. <input data-color="red" />) This is valid, and should be just as easy to implement.
In classic HTML up to and including HTML 4.01, <input></input> is invalid. In practice, browsers ignore the stray end tag. They do not ignore the content between the tags, so <input>foo</input> achieves nothing as compared with <input>foo. HTML5 does not propose to change this.
In XHTML, <input></input> is valid but should not be used on the Web, according to XHTML specs. If you put any content between the tags, it becomes invalid, because the input element has been declared with EMPTY content model.
So you should take a completely different approach. It really depends on what you are trying to achieve, and should be discussed under some other heading. Depending on the problem, the solution could be one of the new HTML5 attributes, or a data- attribute, or a hidden field, or an element hidden some way, or maybe just data in the document tree.