How to select form input based on label inner HTML? - javascript

I have multiple forms that are dynamically created with different input names and id's. The only thing unique they will have is the inner HTML of the label. Is it possible to select the input via the label inner HTML with jQuery? Here is an example of one of my patient date of birth blocks, there are many and all unique except for innerHTML.
<div class="iphorm-element-spacer iphorm-element-spacer-text iphorm_1_8-element-spacer">
<label for="iphorm_081a9e2e6b9c83d70496906bb4671904150cf4b43c0cb1_8">events=Object { mouseover=[1], mouseout=[1]}handle=function()data=Object { InFieldLabels={...}}
Patient DOB
<span class="iphorm-required">*</span>
</label>
<div class="iphorm-input-wrap iphorm-input-wrap-text iphorm_1_8-input-wrap">
<input id="iphorm_081a9e2e6b9c83d70496906bb4671904150cf4b43c0cb1_8" class="iphorm-element-text iphorm_1_8" type="text" value="" name="iphorm_1_8">events=Object { focus=[1], blur=[1], keydown=[1], more...}handle=function()
</div>
<div class="iphorm-errors-wrap iphorm-hidden"> </div>
This is in a Wordpress Plugin and because we are building to allow employees to edit their sites (this is actually a Wordpress Network), we do not want to alter the plugin if possible.
Note that the label "for" and the input "id" share the same dynamic key, so this might be a way to maybe get the id, but wanted to see if there is a shorter way of doing this.
Here I cleaned up what is likely not used...
<div>
<label for="iphorm_081a9e2e6b9c83d70496906bb4671904150cf4b43c0cb1_8">
Patient DOB
<span class="iphorm-required">*</span>
</label>
<div>
<input id="iphorm_081a9e2e6b9c83d70496906bb4671904150cf4b43c0cb1_8">
</div>

You can use the contains selector to select the Patient DOB labels, then find the related input.
$('label:contains("Patient DOB")').parent('div').find('input');
This assumes that the label and input are wrapped in the same div and may not work if more than one pair is in the same div. At least the first part will get you the labels that contain Patient DOB, then you can adjust the later parts to find the correct input element.
For more help on jquery selectors, see the API.
Here is a fiddle demonstrating this.

var getForm = function(labelInnerHtml) {
var $labels = jQuery('label');
$labels.each(function() {
if (jQuery(this).html() == labelInnerHtml) {
var for_id = jQuery(this).attr('for');
return jQuery('#'+for_id);
}
});
return [];
};​​

The class iphorm_1_8 on the input is unique for each form element. So it's simple.
$('.iphorm_1_8');

Related

angular2 capture info from dynamically generated inputs - possible?

Working on an update form which I would like to generate and capture inputs for a variable sized array
The current unhappy version only supports the first three statically defined elements in the constituency array. So the inputs look like this...
<input #newConstituency1 class="form-control" value={{legislatorToDisplay?.constituency[0]}}>
<input #newConstituency2 class="form-control" value={{legislatorToDisplay?.constituency[1]}}>
<input #newConstituency3 class="form-control" value={{legislatorToDisplay?.constituency[2]}}>
and the function to update pulls the values of the form using the static octothorpe tags.
updateLegislator(newConstituency1.value, newConstituency2.value, newConstituency3.value)
But this doesn't allow for a variable sized Constituency array.
I am able to use *ngFor directive to dynamically create input fields for a theoretically infinitely sized constituency array:
<div *ngfor constit of legislatorToDisplay?.constituency>
<input value={{constit}}>
</div>
but have not successfully been able to capture that information thereafter. Any kind assistance would be greatly appreciated.
You just have to have a form object in your component that matches the HTML input components that were created.
Template
<div *ngfor constit of legislatorToDisplay?.constituency>
<input value={{constit}} formControlName="{{constit}}">
</div>
Component
/* create an empty form then loop through values and add control
fb is a FormBuilder object. */
let form = this.fb.group({});
for(let const of legislatorToDisplay.constituency) {
form.addControl(new FormControl(const))
}
Use two-way data binding:
<div *ngFor="constit of legislatorToDisplay?.constituency; let i = index">
<input [(ngModel)]="legislatorToDisplay?.constituency[i]">
</div>

How rails do nested form in one form?

The scenario is that, I want to design a Post form which is used to record what fruit I eat in one meal, include picture, content, many kind of fruit.
The model relationship is that,
Post has_many fruits
Fruit belong_to post
I usee Jquery-ui to make autocomplete in order to help user type their fruit. After they type there fruit tag, it will create a tag under the input field.
Like this
However how to I create this in form? I thought about dynamic nested form, but I don't want there're a lots of form, I wish there would be only one input and do the same thing with dynamic nested form.
Here is the github, please let me know if I need to provide more information.
$(document).on('click','#add_fruit',function(e){
e.preventDefault();
addFruitTag();
});
function addFruitTag(){
var content = $('#content').val().trim();
var fruit = $('#fruit').val().trim();
if(content.length <1 || fruit.length < 1){
alert("Please fill content and fruit");
}else{
$('#fruit_tags').append(
$('<input>')
.attr('type','checkbox')
.attr('name','fruits[]')
.attr('value',$('#fruit').val())
.prop('checked','true')
)
.append(
$('<label>')
.text($('#fruit').val())
)
.append($('<br>'));
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="GET">
Content : <input type="text" id="content" name="content"><br/>
Fruit : <input type="text" id="fruit">
<button id="add_fruit">Add Fruit</button><br/>
<div id="fruit_tags">
</div>
<input type="submit" value="Create Post">
</form>
Note: I don't have much idea about auto complete plugin, so I have created the function addFruitTag(), call it where you are calling your function of adding hash tags of fruits.
And when you will submit the form to the server, you can retrieve the added fruits by accessing the fruits[] variable , which will be an array containing the selected fruits tags.

How to erase the text input that the user typed using JavaScript

<div class = "search ui-widget">
<label for = "keyword"></label>
<input type="text" id="keyword" onkeypress="searchKeyPress(event)" placeholder="Search here" required>
<input type="button" id="btnSearch" onclick="loadDeals('search', keyword.value,'')" />
</div>
$('.search input#keyword').Value('');
Basically what I want is to remove the user's input in the text box after the user clicks another menu tab. I tried $('.search input#keyword').Value(''); and $('.search input#keyword').css("value", ''); but it didn't work.
.val() is the right name of the jQUery method, not Value().
You can use jQuery like this:
$('#keyword').val('');
Or you can use plain javascript like this:
document.getElementById('keyword').value = '';
If there are more input fields beside the ones you posted and you want to clear all inputs you can use:
$('.search input').val('');
Here's a pure javascript solution:
document.getElementById('keyword').value = '';
Since HTML id attributes are supposed to be unique I would recommend not using the '#keyword' id in your jquery selector. The solution does work if there's only one text field, but it isn't scalable to multiple text fields. Instead, I would make 'keyword' a class for the input element and use the selector:
$('.search input.keyword').val('');
This is very similar to the solution Sergio gave except it allows you to control, via the 'keyword' class, which input elements have their values cleared.
Use this
$("the_class_or_id").val("");
Link for this: jQuery Documentation
This is introduced in jQuery API. You can use .value in JavaScript, but in jQuery its val(). It gets the value of the object and to clear the value, just add quotes!
JavaScript code would be:
document.getElementById("id_name").value = "";

Checking the names of elements from an array of objects selected by jquery

I'm a beginner in js and jquery library. I'd like to get an array of input fields with a particular name, and validate input. Each of my input fields have a name like NS[0], NS[1] etc. The total number of fields will have to be determined by the code, since the fields are generated by javascript.
I know that I can have jquery address the individual object like this:
$("input[name=NS\\[0\\]]").val() for <input type="text" name="NS[0]">.
However, how can I get an array of all these similiar elements, from NS[0] to NS[x] where x has to be determined based on how many fields have been generated? I already have other fields with different name patterns sharing the same css class, so using class is not an option. These boxes are in a particular div area, but in the same area are other input fields, so choosing all input boxes of the same area selects them as well.
In other words, how do I use jquery to check the name of each input field, after getting the entire array of input fields, to check each individual name?
Since I have input fields of various names in the area determined by the table id CNTR1, I would select them with $('#CNTR1 input'). I can also select individual fields by using $("input[name=]"). However, what I want to do, is to select everything under $('#CNTR1 input'), and then run a loop on their names, checking whether the names match a predetermined criteria. How can I do that?
The html code:
<table class="table" id="cnservers">
<thead>
<tr>
<th>Type</th>
<th>Preference</th>
<th>Value</th>
<th>Name</th>
</tr>
</thead>
<tr id="CNTR0">
<td>CNAME</td><td><input type="text" name="CN_PREF[0]" value=""></td><td>
<input type="text" name="CN_VAL[0]" value=""></td><td>
<input type="text" name="CN_NAME[0]" value="">
<a class="btn btn-danger" onclick="DelField(this.id);" id="CN_D0" >
<span class="btn-label">Delete
</span>
</a>
<a class="btn btn-primary" onclick="addField('cnservers','CN',10);" id="CN_A0" >
<span class="btn-label">Add
</span>
</td></tr>
</table>
[1]: http://i.stack.imgur.com/bm0Jq.jpg
I must be missing something. Is there a reason you can't use the http://api.jquery.com/attribute-starts-with-selector/?
$('#CNTR1').find('input[name^="NS"]')
Regarding,
However, what I want to do, is to select everything under $('#CNTR1 input'), and then run a loop on their names, checking whether the names match a predetermined criteria. How can I do that?
$("#CNTR1 input").each(function(index, elem) {
var $elem = $(elem),
name = $elem.attr('name');
var nameMatchesCondition = true; // replace with your condition
if (nameMatchesCondition) {
// do something!
}
});
EDIT 1:
Well, id is still an attribute of an html element. So you could do $('[id^="CNTR1"]') ... The value of the id attribute of an element doesn't contain the #. It's only part of the css/jquery selector. When using attribute style selectors, you don't need it. Though I can't comment on the performance of this.
Ideally, you want to attach a second class, say js-cntr to all elements that you created with an id starting with CNTR. Even though different name pattern elements may already have one class, that class is for styling. There is no stopping you from attaching custom classes purely for selection via js. This is an accepted thing to do and which is why the class name starts with js-, to denote that its purely for use via js for selection.
Try this
HTML
<table id="CNTR1">
<tr>
<td>CNAME</td>
<td><input type="text" name="CN_PREF[1]" id="CN_IN[1]"></td>
<td><input type="text" name="CN_VAL[1]"></td>
<td><input type="text" name="CN_NAME[1]"></td>
</tr>
</table>
JS
$(document).ready(function(){
$("#CNTR1 input").each(function() {
console.log($(this).attr("name"));
// Match With predetermined criteria
});
});
Use jQuery's .filter method, with a filter function:
filterCritera = /^CN_NAME\[/; // or whatever your criteria is
var inputs = $('#CNTR0 input');
// you could also cache this filter in a variable
inputs.filter(function(index){
return filterCritera.test(this.name);
}).css('background','red');
jsbin
The markup you posted does not the markup described in your question ( it does not contain NS[0]) but you can substitute it in the reguluar expression above.

How can I create a dynamic form using jQuery

How can I create a dynamic form using jQuery. For example if I have to repeat a block of html for 3 times and show them one by one and also how can I fetch the value of this dynamic form value.
<div>
<div>Name: <input type="text" id="name"></div>
<div>Address: <input type="text" id="address"></div>
</div>
To insert that HTML into a form 3 times, you could simply perform it in a loop.
HTML:
<form id="myForm"></form>
jQuery:
$(function() {
var $form = $('#myForm'); // Grab a reference to the form
// Append your HTML, updating the ID attributes to keep HTML valid
for(var i = 1; i <= 3; i++) {
$form.append('<div><div>Name: <input type="text" id="name' + i + '"></div><div>Address: <input type="text" id="address' + i + '"></div></div>')
}
});
As far as fetching values, how you go about it would depend on your intent. jQuery can serialize the entire form, or you can select individual input values.
.append() - http://api.jquery.com/append/
This is a pretty broad question and feels a lot like 'do my work' as opposed to 'help me solve this problem.' That being said, a generic question begets an generic answer.
You can add new address rows by using the append() method and bind that to either the current row's blur - although that seems messy, or a set of +/- buttons that allow you to add and remove rows from your form. If you're processing the form with PHP on the server side, you can name the fields like this:
<input type='text' name='address[]' />
and php will create an array in $_POST['address'] containing all the values.

Categories

Resources