Find a character inside <label> and set class - javascript

I am trying to find a way to highlight some required fields in a form.
I don't have access to the label settings for this application, so I'd like to try finding a character within the label and change it to be more prominent.
The current label for required fields is set as this example:
<label>First Name *</label>
I would like to find all instances of the asterisk * within label tags in a page and wrap them inside a CSS class so I can either set color or replace with an image.
Is that achievable?
Thank you in advance.

find all labels contain an asterisk,
replace the html with your element
$("label:contains('*')").each(function(){
var r = $(this).html().replace('*',','<sup class="conditions">*</sup>');
$(this).html(r);
});
but this could be done much nicer/faster with css:
label.requiredField:after {
content: "*";
color:#f00;
}
/** your HTML would be **/
<label class="requiredField">First Name</label>
/** and renders like: **/
First Name*
more here: http://www.quirksmode.org/css/beforeafter.html

The :contains selector will give you want you need:
$('label:contains("*")').wrap('<span style="color:red">');

$(label).filter(function () {
return $(this).text().indexOf('*') != -1;
}).each(function () {
$(this).whatEver();
});

Related

Adding different CSS for space and text to an text type input

I have an text type input in an html form as bellow:
<input type="text" id="tag" name="tag">
Now, I want to add style on that input text based on user's input. This style need to be different for text and space.
For example: if someone enters php java python in the input field then I want to style php, java and python with specific background where their internal spaces will have different background.
Is it possible? If possible then how?
The answer is yes and no.
Yes it is possible, but it is not possible with input only.
You cannot put elements inside input tags, but You could have some kind of container which would handle this part for You.
I've attached very simple and naive example, it could be done way better, but it shows You the concept.
Text inside input is being split by space, and new element for each word and space is created.
You could do something like that, but with styled input inside container. Then You should listen for input change. When user press space, You should get the word which user wrote, create new element for word (and also one more for space), append it to container, and clear the input, so it would be ready for next, new word.
const textContainer = document.querySelector('#textContainer')
document.querySelector('#myInput').addEventListener('input', ({ target }) => textToElements(target.value))
const textToElements = (text) => {
const words = text.split(' ')
const wordsElements = words.map(createWordElement)
clearWordsContainer()
wordsElements.forEach(putWordElement)
}
const createWordElement = (word) => {
const element = document.createElement('span')
element.classList.add('word')
element.textContent = word
return element
}
const putWordElement = (element) => {
const spaceElement = document.createElement('span')
spaceElement.classList.add('space')
spaceElement.textContent = ' '
textContainer.appendChild(element)
textContainer.appendChild(spaceElement)
}
const clearWordsContainer = () => textContainer.innerHTML = ''
.word {
color: #FFF;
background: #333;
}
.space {
background: #999;
}
<div class="container">
<div id="textContainer"></div>
<input id="myInput" type="text" />
</div>
You can't give style to text inside an input directly.
I think what you are looking for is an UI element commonly named "tags input" or "chips input" or "pills input"
You might use some javascript or better ("better" being a personal appreciation, see comments below) a js library to input tags/pills like this one
https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/ (see title Categorizing tags, which uses different colors for each tag)
You can google for others using those names I gave you.

How to get value of another input field using javascript

How to find the value of text field using onblur() in next input field.
I tried:
function get_value() {
var inv_nrs;
inv_nrs = document.getElementsByTagName('text1').value;
alert(inv_nrs);
}
text1 is name of input which I am trying to get value.
text2 is name of input where onblur() is triggered.
Two problems:
To get elements by their name attribute, use document.getElementsByName(), not document.getElementsByTagName.
Since these functions return a collection, not a single element, you have to index them to get a specific element.
So the function should be:
function get_value() {
var inv_nrs;
inv_nrs = document.getElementsByName('text1')[0].value;
alert(inv_nrs);
}
Here's a simple snippet which illustrates a way to do this.
(You may wish to use alert in place of console.log)
document.getElementById("text2").onblur = function() {
console.log(document.getElementById("text1").value)
}
<input type="text" id="text1" value="123" />
<input type="text" id="text2" />
Are you looking for an element with id = "text1" or real name = "text1"?
At least if it's their id try getElementById("text1"), that returns one single element. If you talking about the name-attribute, take getElementByName("text1"), this may return more than one element (if there are more then one with the same name).
i think you want this???
function get_value()
{
var inv_nrs;
inv_nrs = document.getElementById('txt1').value;
document.getElementById('txt2').value=inv_nrs;
}
<input type="text" id="txt1" >
<input type="text" id="txt2" onblur="get_value()">
If you search with tagname then you need to insert a tagname:
document.getElementsByTagName('input')[whole_number].value which also
returns a live HTMLCollection
Eg. document.getElementsByTagName("input")[0].value; ,if this is the first textbox in your page.
You can get the value of an html element also on different ways:
document.getElementsByName('text1')[whole_number].value which also
returns a live NodeList
Eg. document.getElementsByName("searchTsxt")[0].value; if this is the
first textbox with name 'searchtext' in your page.
You can also get element by Id:
document.getElementById('IDHere').value to get the value of desired
box
You can also get it by way of Classname:
Use document.getElementsByClassName('class_name')[whole_number].value
which returns a Live HTMLCollection
Good luck

Format text as user inputs in a contenteditable div

I'm attempting to make a page that allows users to input text and it will automatically format the input -- as in a screenplay format (similar to Amazon's StoryWriter).
So far I can check for text with ":contains('example text')" and add/remove classes to it. The problem is that all of the following p tags inherit that class.
My solution so far is to use .next() to remove the class I added, but that is limited since there might be need for a line break in the script (in dialogue for instance) and that will remove the dialogue class.
$('.content').on('input', function() {
$("p.input:contains('INT.')").addClass("high").next(".input").removeClass("high");
$("p.input:contains('EXT.')").addClass("high").next(".input").removeClass("high");
});
I can't get || to work in the :contains parameter either, but that's the least of my issues.
I have a JS fiddle
I've worked on this for a while now, and if I could change only the node that contains the text (INT. or EXT. in this example) and leaves the rest alone that would work and I could apply it to the rest of the script.
Any help would be appreciated, I'm new to the stackoverflow so thank you.
See the comments in the code below for an explanation of what's going on.
Fiddle Example
JQuery
var main = function(){
var content = $('.content');
content.on('input', function() {
$("p.input").each(function() {
//Get the html content for the current p input.
var text = $(this).html();
//indexOf will return a positive value if "INT." or "EXT." exists in the html
if (text.indexOf('INT.') !== -1 || text.indexOf('EXT.') !== -1) {
$(this).addClass('high');
}
//You could include additional "if else" blocks to check and apply different conditions
else { //The required text does not exist, so remove the class for the current input
$(this).removeClass('high');
}
});
});
};//main close
$(document).ready(main);

Styling input field of dynamic ID using getElementById

I have some input fields that has its id's number changes dynamically.
For example, the below code shows an input field that has "id="field14". The word (field) in the id does not change, but the (number) is changing dynamically. So it may be field14, field13, or field20, etc, and there is no limit for numbers.
<input type="text" name="field[14]" id="field14" value="" size="30" style="height: 24px;">
I'm using the following code to style the input field:
document.getElementById("field14").style.height = "24px";
Note, the application's PHP code is encoded & I'm editing in smarty template.
The input code in the template is like this: {$field.input} So when I inspect element on the live page it shows the above code of the input with the dynamic number of the id.
I want a way that allow me to style any input field of the page that starts with the word (field) and ends with a dynamic (number). Any suggestions please?
For a pure CSS approach, I would check the name instead, so you should only look for input elements whose attribute starts with field[ and ends with a closing bracket ].
e.g.
input[name^="field["][name$="]"] {
...
}
From the code you posted you can reasonably suppose that the name of all the elements containing a numeric index inside brackets [] are also the same elements with that dynamic index as a part of your id.
otherwise you may write a more complex set of selectors looking for an id starting with field and ending with a digit [0..9]
e.g.
input[id^="field"][id$="0"],
input[id^="field"][id$="1"],
input[id^="field"][id$="2"],
input[id^="field"][id$="3"],
input[id^="field"][id$="4"],
input[id^="field"][id$="5"],
input[id^="field"][id$="6"],
input[id^="field"][id$="7"],
input[id^="field"][id$="8"],
input[id^="field"][id$="9"] {
...
}
or even combine both the methods
input[name^="field["][name$="]"][id$="0"],
input[name^="field["][name$="]"][id$="1"],
...
input[name^="field["][name$="]"][id$="9"] {
...
}
You can use an attribute selector:
input[id^=field] {
/* Styles */
}
It will match all input elements whose id attribute begins with "field". Using some separator between "field" and the number may be better to prevent matching things like "fieldone".
input[id^=field] {
background: red;
}
<input id="field1" />
<input id="field2" />
<input id="field3" />
<input id="field15" />
<input id="field99" />
i strongly recommand using a class attribute:
HTML
<input type="text" class="fields" name="field[14]" id="field14" value="" size="30" style="height: 24px;">
CSS
.fields {
/*style*/
}
I want a way that allow me to style any input field of the page that
starts with the word (field) and ends with a dynamic (number). Any
suggestions please?
This is a very specific question that wants us to key on the fact that the id starts with "field" and ends in a dynamic number. IMHO this solution answers your question exactly as asked using only CSS, plus it doesn't require you to change your HTML or add a class attribute (although this would be much better).
This CSS code will find any <input> tag that has an id starting with "field" and ending in a number. It will also exclude those that start with "field" but do not end in a number.
input[id^='field'][id$='0'],input[id^='field'][id$='1'],input[id^='field'][id$='2'],input[id^='field'][id$='3'],input[id^='field'][id$='4'],input[id^='field'][id$='5'],input[id^='field'][id$='6'],input[id^='field'][id$='7'],input[id^='field'][id$='8'],input[id^='field'][id$='9']
{
// styling code
}
Demo code: http://jsfiddle.net/Drakes/7wpnL/671/
If you need JS approach:
http://codepen.io/knitevision1/pen/LEaXxW
var num = 2;
document.getElementById("input" + num).style.backgroundColor = "blue";
If I get you right, you need all your new input look somewhat unique or something.
You can think of getting a number of the currently presenting inputs, then get the last of them, then attach your style based on what you want it to look like.
Using jquery:
var inputs = [];
function getFields(){
$('input').each(function() {
if($(this).attr('id').substring(0,5)=='field'){
inputs.push($(this));
}
});
}
you can modify each input inside the "each" loop, or you can use the "inputs" variable.
Demo: http://jsbin.com/kubaku/1/edit?html,js,output
JS
var inputs = document.getElementsByTagName('input');
var ID = 'field';
var i;
for(i = 0; i < inputs.length; i++) {
var input = inputs[i];
var regex = new RegExp("^" + ID);
if(regex.test(input.id)) {
input.style.border = '1px solid #c00';
}
}

Change all id's in HTMLDivElement using jQuery

I am using jQuery to dynamically append a Django formset.
I am using a link to add another form identical to the one above it. I do this with the following code:
var row = $("."+class_name).first().clone(true);
row.find('input').val('');
$(row).removeAttr('id').hide().insertAfter("."+class_name).last().slideDown(300);
Every label in row[0] (which is a HTMLDivElement) is id_cur-0-... And everytime I use this jQuery function to add a div, I need every id to increment the number after cur. So the first time I click it every item would have id_cur-1... And the next time they would have id_cur-2... And so on.
If I could treat the HTMLDivElement like a string I could use regex to basically find every occurrence of "cur-\d". How would I do this? Or is there a better way (because this kind of seems like a hack).
Here's what my HTML looks like:
<div class="item1">
<label style="display:inline-block;" for="id_cur-0-cur_child_name">
Name:
</label>
<input style="display:inline-block;width:10%" class="textinput textInput form-control" id="id_cur-0-cur_child_name" name="cur-0-cur_child_name" type="text" />
<label style="display:inline-block;" for="id_cur-0-cur_child_sex">
Sex:
</label>
<input style="display:inline-block;width:10%" class="textinput textInput form-control" id="id_cur-0-cur_child_sex" name="cur-0-cur_child_sex" type="text" placeholder="[M / F]" />
<label style="display:inline-block;" for="id_cur-0-cur_child_dob">
DOB:
</label>
<input style="display:inline-block;width:10%" class="textinput textInput form-control" id="id_cur-0-cur_child_dob" name="cur-0-cur_child_dob" type="text" placeholder="e.g. 12/25/2014" />
</div>
Would this do?
var last_id = $("."+class_name).last().attr("id").split("-")[1];
fiddle
UPDATE
Hi there, the ev.preventDefault only serves the purpose of preventing the default behaviour of the anchor. It stops the default action of an element from happening.
I saw your html and here you have a new fiddle
Javascript code (commented):
$("#clone").click(function (ev) {
ev.preventDefault();
var row = $(".item1").last().clone(true);// Last item1
var last_id = $(row).find("input:first").attr("id");// Grab first input id (it contains the important part: the number)
row.find('input').val('');
$.each(row.find('input'), function (index, item) {// Change id of all inputs inside the cloned element.
var id = (+(last_id.split("-")[1])+1), // Grab the number and increase it.
new_id = $(item).attr("id").replace("id_cur-" + last_id.split("-")[1], "id_cur-" + id);// Replace ids with the new number.
$(item).attr("id",new_id);// Asign the new id to the inputs. You'll have to do more or less the same to the labels if you like.
});
$(row).removeAttr('id').hide().insertAfter(".item1:last").slideDown(300);// Insert after the last item1 element. Otherwise it'll insert after all elements with class .item1
});
Hope it helps.
Kind regards.
Instead, you can use id_cur as the class name, and the specific id with the id attribute as such:
var last_row = $("."+class_name+":last");
var new_row = last_row.clone(true);
new_row.attr('id', new_row.attr('id')+1);
new_row.find('input').val('');
new_row.removeAttr('id').hide().insertAfter(last_row)
new_row.slideDown(300);
You simply have to increment the id attribute with the last one + 1.
Just for clarification: You were using first() to select the first matched element and clone it in var row = $("."+class_name).first().clone(true);, but in this case, if we want to increment the id accordingly, we must clone the latest element added.
Hope this helps !
Cheers,
I could use regex to basically find every occurrence of "cur-\d".
Use the JQuery regex selector to find all id or whatever attr.
Select all the label tag element in which the for attribute start with id-cur-
$("label[#for^=id-cur-]")
Select all input tag element with id beginning with id-cur-
$("input[#id^=id-cur-]")
Hope this may help to select the dom element with regex.

Categories

Resources