How to get id of a dynamic input field in javascript - javascript

I want to create a dynamic form where I also apply JavaScript to the dynamic elements.
What I want to do right now is figure out which field (stored in array or whatever data structure) in JavaScript has been clicked so that I can apply the script to that particular field.
The HTML looks like this:
<div class="triple">
<div class="sub-triple">
<label>Category</label>
<input type="text" name="category" id="category" placeholder="Classes/Instances" required/>
<ul class="cat-list"></ul>
</div>
<div class="sub-triple">
<label>Relation</label>
<input type="text" name="relation" id="relation" placeholder="Properties" required/>
<ul class="rel-list"></ul>
</div>
<div class="sub-triple">
<label>Value</label>
<input type="text" name="value" id="value" placeholder="Classes/Instances" required/>
<ul class="val-list"></ul>
</div>
</div>
This "triple" div is dynamic and I want to create as many "triples" as the user wants, that also means the input fields of inside the "triple" section increase as well.
I'm confused on how to add javascript to one element of the input. For example I have inputs: category, relation and value and the user wanted 2 or more triples then the input ids could look like category2, relation2 and value2 or something similar to that.
let category = document.getElementById("category");
category.addEventListener("keyup", (e) => {
removeElements();
listDown(category, sortedClasses, ".cat-list")
});
If I lets say clicked on category2 for instance how do I tell that to my javascript since these fields are completely dynamic.
Summary: The user is adding repeat sections of triples (containing 3 input elements), where the id of each input element is generated dynamically. My script above works for the first triple section only as the ids are fixed, as for successive "triple" section the id of the fields get changed. How do I identify (see which element has been clicked) and get these dynamic ids

Try listening to the parent element and then using the event's target to figure out the identity of the input. Since the child elements events will bubble up you'll be able to listen to all children
e.g.
let parentElement = document.querySelector(".triple");
parentElement.addEventListener("click", (e) => {
console.log(e.target.id);
});

You can use the onfocus event
<div class="triple">
<div class="sub-triple">
<label>Category</label>
<input type="text" name="category" id="category" placeholder="Classes/Instances" onfocus="onFocusCategoryInput()" required/>
<ul class="cat-list"></ul>
</div>
<div class="sub-triple">
<label>Relation</label>
<input type="text" name="relation" id="relation" placeholder="Properties" onfocus="onFocusRelationInput()" required/>
<ul class="rel-list"></ul>
</div>
<div class="sub-triple">
<label>Value</label>
<input type="text" name="value" id="value" placeholder="Classes/Instances" onfocus="onFocusValueInput()" required/>
<ul class="val-list"></ul>
</div>
</div>

Related

how to generate the id of a div dynamically using javascript

I have a (+) sign and a (-) sign. If the user clicks on the + sign than whatever their in the row will automatically get generated the same with new id.
Now when user click on + sign than div id and text box under it will get changed.
Code below for div as follows:
<div class="row" id="Div0">
<div class="col-md-3">
<div class="form-group">
<label for="name">Last Name</label>
<input type="text" class="form-control" id="txtLastName0" placeholder="Enter name" required="required" />
</div>
</div>
<div class="col-md-9"></div>
</div>
Now when user clicks on + sign the new row with text box with new id txtLastName1 will get generated.
Now on click of + sign how do i get new id of textbox and a div with new row.
Div1 and textbox1 will get generated
Basically what you should do is, keep the markup you want to generate as a template in your DOM and when user clicks the "Add" button, clone this markup and append to the DOM (to a container div). then update the Id's of the input and divs as needed.
A simply sample would be like
<div class="row" id="template" style="display: none;">
<div class="col-md-3">
<div class="form-group">
<label for="name">Last Name</label>
<input type="text" class="form-control lname" id="txtLastName"
placeholder="Enter name" required="required" />
</div>
</div>
<div class="col-md-9"></div>
</div>
<button id="btnAdd">+</button>
<div id="container"></div>
Now wire up a click event handler to the Add/+ button. You may use the jQuery clone() method.
$(function () {
$("#btnAdd").click(function(e) {
e.preventDefault();
var childCount = $("#container").children().length;
var c = $("#template").clone().show();
c.attr("id", "Div" + childCount );
c.find(".lname").attr('id', 'txtLastName' + childCount);
$("#container").append(c);
});
});
For deleting, you can add a event handler on the delete button and remove the specific div from dom. jQuery remove() method will do it. Use closest() and find as needed to get the correct div to remove.
Here is a working simple jsbin sample for your reference

Can't select and hide any previous element

I'm about lose my mind with this problem. No form of jQuery selector seems to work in dynamically finding any elements above the link. I'm trying to access an element above the link and hide it. Using things like parent(), prev(), before(), closest(), ect. will show a non-null object but it won't respond to the hide() method.
<div class="row">
<div class="col-xs-5">
<div id="test_fields">
<li id="test_input" class="string input optional stringish">
<label class="label" for="test_input">Ingredient name</label>
<input type="text" name="test_input" value="afsfasf" id="test_input">
</li>
</div>
<input type="hidden" id="recipe_recipe_ingredients_attributes_0__destroy" name="recipe[recipe_ingredients_attributes][0][_destroy]">
Remove Ingredient
</div>
</div>
function remove_fields(link)
{
$(link).prev("input[type=hidden]").val('1'); // this doesn't work
var divToHide = $(link).prev('div');
$(divToHide).hide() // this doesn't work
//$('#test_fields').hide(); //this works
}
Try replacing the link as below:
Remove Ingredient
I'm not sure. But maybe this is the problem. Because I remember that I have had problem with 'this'previously and when I replaced that, it performed the job.
you can try .closest() and .find()
function remove_fields(link) {
$(link).closest('div[class^="col-xs"]').find("input[type=hidden]").val('1');
var div_to_hide = $(link).closest('div[class^="col-xs"]').find('#test_fields');
$(div_to_hide).hide();
//$('#test_fields').hide(); //this works
}
You can't change hidden input's "value" attribute by using .val(). You need to use:
$(link).prev("input[type=hidden]").attr('value', '1');
As I'm not really sure what do you want to do with this input, I'll just let it go like this.
.prev() fn goes only one previous element in the structure. As input is a <a>'s previous element, you can't select div like that. You can use .siblings() for instance.
$(link).siblings('div').hide();
If you break the code in pieces, it gets easier.
First I took the 'Link', from it I grabbed the nearest div above it, then I picked up the input.
I did not make many changes to your code.
function remove_fields(link)
{
var $link =$(link);
var $divToHide = $link.closest('div');
$divToHide.find("input[type='hidden']").val('1');
$divToHide.hide()
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="row">
<div class="col-xs-5">
<div id="test_fields">
<li id="test_input" class="string input optional stringish">
<label class="label" for="test_input">Ingredient name</label>
<input type="text" name="test_input" value="afsfasf" id="test_input">
</li>
</div>
<input type="hidden" id="recipe_recipe_ingredients_attributes_0__destroy" name="recipe[recipe_ingredients_attributes][0][_destroy]">
Remove Ingredient
</div>
</div>

JQuery detects focusOut even if I still focus on input inside the same div. How to change it?

This is my code:
Javascript:
$(".test").on("focusout", function (e) {
$("#output").append("Lost focus<br>");
});
HTML:
Inputs inside div:
<div class="test">
<input type="text" />
<input type="text" />
</div><br>
Inputs outside div:<br>
<input type="text" />
<div id="output">
</div>
I want to detect if user leaves "div.test". Unfortunately, "focusout" works also when I move focus to other object inside this div.
Look at this fiddle: http://jsfiddle.net/Piotrek1/wfukje3g/6/
Click on first input and use Tab to switch through textboxes. "
Lost focus" should appear only if user move out from the div, but it happens always. Why is that and how to change it?
The $ operator returns a collection. You have two inputs inside the <div class="test">. So it matches all elements and children with the .test class.
I think what you want two divs with separate input elements and two different classes OR, use an ID on the actual input element so the $ operator only matches the input id you want this event to fire on. http://jsfiddle.net/wfukje3g/7/
$("#test").on("focusout", function (e) {
$("#output").append("Lost focus<br>");
});
<div class="sometest">
<input id="test" type="text" />
<input type="text" />
</div><br>
Inputs outside div:<br>
<input type="text" />
<div id="output">
</div>
I have implemented piece of code to handle div focus out
$(document).ready(function () {
var count = 1;
$("#name").focusout(function (e) {
if($(this).has(e.relatedTarget).length === 0) {
$("#output").append("<label style='width:100%;'>"+ count++ +" Name div focus out </label>");
}
});
});
Inputs inside div:
<div id="name" class="test">
<input type="text" id="firstname"/>
<input type="text" id="lastname"/>
</div>
Inputs outside div:<br>
<input type="text" id="dob"/>
<div id="output" style="width:100%"></div>
In this piece of code I have used relatedTarget.
relatedTarget will provide the next focused element If next element is not the child of this div then it is div focus out.
Try this in your code.
I hope this will be helpful.
Thanks
JSFIDDLE LINK - Sample code

Complex selecting of specific inputs generated by for-loop

I'm trying to select some specific inputs in a list of inputs generated by a for-loop, inside some divs also generated by for-loop. That means that the selecting process is a bit messy and difficult, because the ids are dynamic.
So, here is a sample of what I have, every id is generated by a for-loop:
<div id="block0">
<input id="special0-0" class="block"></input>
<input id="special0-1" class="block"></input>
<input id="special0-2" class="block"></input>
<input id="special0-3" class="block"></input>
</div>
<div id="block1">
<input id="special1-0" class="block"></input>
<input id="special1-1" class="block"></input>
<input id="special1-2" class="block"></input>
<input id="special1-3" class="block"></input>
</div>
<div id="item0">
<input id="special0-0"></input>
<input id="special0-1"></input>
<input id="special0-2"></input>
<input id="special0-3"></input>
</div>
<div id="item1">
<input id="special1-0"></input>
<input id="special1-1"></input>
<input id="special1-2"></input>
<input id="special1-3"></input>
</div>
I want to select the inputs with id="special0-2 AND id="special1-2" BUT NOT the ones which have class="block".
I've tried several possibilities, including these two that should work to me:
var item2 = $("div[id|='item'] > input[id$='-2']");
var item2 = $("input[id|='special'][id$='-2'][class!='block']");
The problem is, for each option, console.log(item2) returns 0 and I can't apply the javascript changes I planned on them after. Thanks for your ideas :)
JSFiddle
This might be it:
$('[id^="item"]').children('[id$="-2"]:not(.block)'); // full
$('[id^="item"] > [id$="-2"]:not(.block)'); // short
First select the divs with the id's that start with 'item', in those find those with the id ending with '-2'.
I suggest you give the root items a class. If you always want the 3rd one, combined it would be:
$('.classname').children('div:nth-child(3)'); // full
$('.classname > div:nth-child(3)'); // short

how can I add a wildcard with jquery binding

how can I add a wild card into this jquery bind event so that form fields with 'PauNumber' are ignored? This field is repeated for each entity. Unfortunately I can't easily assign a css class to it because the text box is created server side.
many thanks
<div class="PassengerWrapper">
<input type="text" value="" name="PauNumber0" id="PauNumber0">
</div>
<div class="PassengerWrapper">
<input type="text" value="" name="PauNumber1" id="PauNumber1">
</div>
<div class="PassengerWrapper">
<input type="text" value="" name="PauNumber2" id="PauNumber2">
</div>
$('.PassengerWrapper input[type=text], .PassengerWrapper select').not(':hidden').each(function () {
You can do it inside the .not('selector') to filter the elements you don't want
$('.PassengerWrapper input[type=text], .PassengerWrapper select').not(':hidden,input[name*=PauNumber]').each(function () {
You can use [name*=PauNumber] or [id*=PauNumber]
Here's an example fiddle for you http://jsfiddle.net/XQWmf/
Also link to the different selectors

Categories