get sibling that has id - javascript

So I have the following structure:
<div id="some id">
<div>
<input id="some other id" ....>
.....bunch of other inputs with no id field....
<select onclick="findSiblingWithId()">
</div>
<div>
<input id="some other id" ....>
.....bunch of other inputs with no id field....
<select onclick="findSiblingWithId()">
</div>
<div>
<input id="some other id" ....>
.....bunch of other inputs with no id field....
<select onclick="findSiblingWithId()">
</div>
So in my findSiblingWithId i don't know the id I'm looking for, all I know is that for the other components in the same div, only one will have an id. How can I get that ?
Edit:
Since it seems I didnt explain well enough I'll try to add more info. So I want for example when the select component changes (here it could be a button or anything, it doesnt matter) to get the corresponding <input id="some other id" ..> from the same div.
Like I tried to explain above, I have one huge div, the <div id="some id">, now this contains a number of smaller <div> without ids.
Each of these smaller divs will have ONE inputfield with an ID and a bunch of other without an ID. Now on an action, doesn't matter if a button click or whatever, from a component located IN THE SAME div (I thought the correct work would be 'sibling') is there a way I can find the input that has an ID attribute?
Regards,
Bogdan

You could iterate over all children of the parent:
function findSiblingWithId(element) {
var siblings = element.parentNode.children,
sibWithId = null;
for(var i = siblings.length; i--;) {
if(siblings[i].id) {
sibWithId = siblings[i];
break;
}
}
if(sibWithId) [
// found it
}
};
You have to pass the clicked element (I hope you have a proper select field);
<select onclick="findSiblingWithId(this)">
Consider to attach the event handler for the change event, if you want to have it triggered when the user selected a value.

Recursively iterate through the parent div and add logic to separate the inputs that have IDs

function findSiblingWithId(element) {
var sibling = null;
if (element.parentNode != null) {
sibling = element.parentNode.nextSibling;
// Then go through the child elements of your sibling node and get the one with an id
}
}

Using jQuery:
<!--Modify HTML so input is -->
<select onclick="findSiblingWithId(this)">
findSiblingWithId(elem){
return $(elem).siblings("[id]"); //if you need all
//return $(elem).siblings("[id]:eq(0)"); //if you need only first
}

The most direct way to get the value that has this id among the siblings is to use the sibling's filter like this:
let my_id = ...
$(this).siblings(`div[id=${my_id}]`)

Related

getElementsByFieldName ? Get all elements of a radioenum that have a certain field name

I have a radioenum html that looks like
<div class="col-xs-12" type="radioenum" field="arr_c">
// elements
</div>
I'm trying to get the elements it contains, but not sure how to proceed
There's no function called getElementsByFieldName that can be called and class name is not unique so I can't use getElementsByClassName
Use either querySelector if you want to grab the first element on the page that matches the selector or querySelectorAll if you want to grab all of them.
(NB: enum is a reserved word so you can't call your variable names that I just found out)
const radios = document.querySelectorAll('[type="radioenum"');
radios.forEach(radio => console.log(radio.textContent));
<div class="col-xs-12" type="radioenum" field="arr_c">
Test 1
</div>
<div class="col-xs-12" type="not-radioenum" field="arr_c">
Test 2
</div>
<div class="col-xs-12" type="radioenum" field="arr_c">
Test 3
</div>
Edit
One thing I've just noticed is that both type and field are invalid attributes. You can use type on a number of elements but div is not one. So, first you should switch those attributes to data- attributes. You can pick up the data-attribute in the same way and then, in the loop, you can destructure the field attribute out from the current element and check its value.
const radios = document.querySelectorAll('[data-type="radioenum"]');
radios.forEach(radio => {
const { dataset: { field } } = radio;
if (field === 'arr_c') {
console.log('Found arr_c');
} else {
console.log(radio.textContent)
}
});
<div class="col-xs-12" data-type="radioenum" data-field="arr_a">
Test
</div>
<div class="col-xs-12" data-type="not-radioenum" data-field="arr_b">
Test 2
</div>
<div class="col-xs-12" data-type="radioenum" data-field="arr_c">
Test 3
</div>
Use querySelector() instead and you can select the element by its attributes. It will return the first matching Element, just like getElementById().
Example:
document.querySelector("[type=radioenum]");
If you need to capture multiple inputs, you can also use querySelectorAll(), but it will return a NodeList, instead of an Element:
document.querySelectorAll("[type=radioenum]");

document.body.appendChild() will work but not when I try to append to a specific element in the body

I have this function which I call onclick whenever a checbox is clicked, but for some reason I cant add it to the document. Ive changed the last line to a bunch of different things, but for some reason the only way I can add it to the document is to use document.body.appendChild(frag);
I want to be able to add it into a specific place, so I tried to get the target of the event by id. There are a lot more boxes so I wanted to get the ID of the box being clicked and add the elements underneath it, and my code had been working to append the children, just nothing actually showed up... I included one of the checkboxes in my html.
<form id="lang" class="poll" onsubmit="langCheck()">
<h1 class="background ulin center">What programming languages do you know?</h1>
<input class="lbox" id = "box1" type="checkbox" value="Assembly" onclick="addSelect(this)">Assembly<br>
</form>
function addSelect(e) {
var target = document.getElementById(e.id);
var lol = e.id;
var frag = document.createDocumentFragment();
var select = document.createElement('select');
var optgroup = document.createElement('optgroup');
var options = [
document.createElement('option'),
document.createElement('option'),
document.createElement('option')
];
//Define content for options
optgroup.label = "Level of expertise?";
options[0].value = "Beginner";
options[1].value = "Intermediate";
options[2].value = "Expert";
frag.appendChild(select);
select.appendChild(optgroup);
//add all options to the optgroup node
options.forEach(function(element) {
optgroup.appendChild(element);
});
document.body.querySelector('#box1').appendChild(frag);
}
Input elements can't have children. If you want the fragment to appear after the input, you would need to insert it into the document as a sibling of the element. Unfortunately for HTMLElement, there is no built in "insertAfter", only insertBefore. you need to insert the new element before the element's nextSibling. If there isn't a next sibling, it's safe to assume the element is the last child (unless it isn't in the dom), so you can then just append it.
Something like this should do the trick:
function insertAfter(newElement,refElement){
if(refElement.nextSibling)refNode.parentElement.insertBefore(newElement,refElement.nextSibling);
else refNode.parentElement.appendChild(newElement);
}
insertAfter(document.getElementById('#box1'),frag);
You can do this by another way, you need to change the visibility of elements when the checkbox is checked, so you can addEventLister to checkbox and change the style of elements when it triggers the event.
const checkBox = document.getElementById('box1')
checkBox.addEventListener('change', function(){
const elements = [...document.getElementsByClassName("visibility")]
if(this.checked){
elements.forEach(element => {element.style.display="initial"})
}else{
elements.forEach(element => {element.style.display="none"})
}
})
<form id="lang" class="poll" onsubmit="langCheck()">
<h1 class="background ulin center">What programming languages do you know?</h1>
<input class="lbox" id = "box1" type="checkbox" value="Assembly">Assembly<br>
<p class="visibility" style="display:none"><input name="level" type="radio" id="radioButton1"> Expert</p>
<p class="visibility" style="display:none"><input name="level" type="radio" id="radioButton2"> Middle</p>
<p class="visibility" style="display:none"><input name="level" type="radio" id="radioButton3"> Beginner</p>
</form>

How to select text value from a variable div id tag?

<div id="Modal<%= index %>">
<div>
<input type="text" id="textvalue">
</div>
</div>
In the above code I need to get value of text field but the problem coming is the div id is variable according to index i.e it may be 'Modal0' or 'Modal1' or 'Modal"n"' depending on value of index. So, if i write $(#textvalue).val() then it is always giving the text entered in id 'Modal0'. What will be solution for this? And the big issue is that I can not use 'Modal0' or 'Modal1' ... id because that is generated dynamically.
you can use closest jquery function like that make dive id is different.
closest will fetch the parent tag.
$(diveid).closest("diveid").inoutid.val();
You should include the parent div in the query as well, for example:
$("#Modal0 input").val();
First you should select the div you´re looking for , then find it's text-input
$('#Modal0').find('#textvalue').val();
$('#Modal1').find('#textvalue').val();
Im not sure if this is what you're trying to do, but if the clicking of buttons will only affect the ID of the same container div of the input.textvalue element then this will do the trick:
$('div[id^=Modal] #textvalue').val());
DEMO:
$(function(){
$('a').on('click', function(e) {
const ID = $(this).attr('href')
const counterID = ID.substring(ID.length-1);
const targetID = $('div[id^="Modal"]').attr('id');
$('div[id^="Modal"]').attr('id', 'Modal'+(counterID-1));
console.log('DIV ID:', 'Modal'+(counterID-1));
});
$('button').on('click', function(){
console.log('DIV ID: ' + $('div[id^=Modal]').attr('id'), ' ,TEXT VAL: ' + $('div[id^=Modal] #textvalue').val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Modal 1
Modal 2
Modal 3
<div id="Modal">
<div>
<input type="text" id="textvalue">
</div>
<button>submit</button>
</div>

Attempting to preview form input jQuery

I am attempting to preview my name and step element in my form, so the user can see if they have made a mistake. I am able to preview the step however the name just won't work. Can anyone see why?
http://jsfiddle.net/pocockn/rw54b/
$(document).ready(function() {
var commentNode = $('#lp-step'),
nameNode = $('#lp-name'),
name = $('#name');
$('#live-preview-form input, #live-preview-form textarea').bind('blur keyup',function() {
commentNode.text($('#step_1').val());
commentNode.html($('#lp-step').html().replace(/\n/g,'<br />'));
if($('#name').val()) {
nameNode.text(name.val() + ' says:');
}
else {
return false;
}
});
});
You can't have two elements with the same ID, if you do it will only select the first element it finds. (in this case its the div which is always empty and never runs your if statement). You have your div with id=name and your input. So I changed your div id to nameDiv instead.
Id's should be unique to avoid confusion.
<div id="nameDiv">
<label for="name">Enter recipe name:</label>
<input type="text" id="name" name="name">
<br />
</div>
http://jsfiddle.net/trevordowdle/rw54b/1/

Place div.innerHTML as a hidden form value

I have a long page with identical section I am attempting to combine into one that has:
TITLE
description
form
I have working mouseovers that change the title and description, but need a solution to change the value of a hidden form input to the new titles when changed.
HOW do I get the hidden form value to change onmouseover to equal current TITLE.value?
Milestones
PHP
function changeContent(id, msg) {
var el = document.getElementById(id);
if (id) {
el.innerHTML = msg;
}
}
FORM
<input type="hidden" value="" name="category" />
Is this what you're looking for?
document.getElementById('hiddenInputId').value = msg;
Your hidden element doesn't have an Id, so you can use following:
var elems = document.getElementsByName('category');
elems[0].value = <<new value>>
getElementsByName always returns an array so you have to pickup first element and set its value.
Cheers !!

Categories

Resources