How to get current element in order to select with javascript? - javascript

I've got the follwoing HTML structure (I do not have the IDs of the following elements because they are dynamically created):
<fieldset>
<div class="classA">
<select onchange="updateInputBox()">
<option>a</option>
<option>b</option>
<option>c</option>
<option>d</option>
</selects>
</div>
<div class="classB">
<input data-myAttribute="case1">
</div>
<div class="classC">
<a type="button">
<i class="fa fa-remove">x</i>
</a>
</div>
</fieldset>
The filedset and it's children is dynamically created. I want to change the attribute in the inputBox depending on what the user selected in the selectBox.
Here is an example how I would have done if the element fieldset would not have been dynamic (the following contains elements have IDs, but only because I want to demonstrate what I want; in reality I don't have IDs because they are dynamically created by clicking a button, that I do not show here):
https://jsfiddle.net/thadeuszlay/6bsgazvv/4/
But unfortunately I don't have the id of the fieldset, because it is dynamically created. Is there a way how you can get the position of the current element?
I tried to pass itself in the updateInputBox-function:
<select id="selectBox" onchange="updateInputBox('+ this +')">
I also tried with jQuery:
$(this).parent().parent()
but in both cases the console would say
"Unexpected identifier"
Update:
Inside the function doing something like this (currentElement is the selectBox/DropDownBox):
currentElement.parent().parent().setAttribute("data-myAttribute", "hello");
Uncaught TypeError: selectBox.parent is not a function

You can use jquery 'closest' for this as below.
HTML
<select id="selectBox" onchange="updateInputBox(this)">
JS
function updateInputBox(selectElm) {
var inputElm = $(selectElm).closest('fieldset').find('input');
inputElm.attr('data-myAttribute', $(selectElm).val());
}
// instead of inline onchange event and the above code, you can use the below to trigger the event
$(document).on('change', 'fieldset select', function () {
var inputElm = $(this).closest('fieldset').find('input');
inputElm.attr('data-myAttribute', $(this).val());
});

In updateInputBox, simply look at the selectedIndex of #selectBox

<select id="selectBox" onchange="updateInputBox(this)">
function
function updateInputBox(dropdowntBox) {
var inputBoxField = document.getElementById("inputBox").setAttribute("data-myAttribute", dropdowntBox.value);
}

Here is jquery version:solution
You need to trigger change() event for select with ID selectBox
$(document).on('change','select',function(){
var value=$(this).val();
$(this).parents('fieldset').find('input').attr('data-myAttribute',value);
});

Related

Remove option item from dataset

Am trying to achieve the following:
The user can select a resource name from a datalist.
The selected resource name will be created in another div.
At the same time, the resource name should be removed from the original datalist. Just to prevent from having the user selecting the same resource name again.
I used the following HTML Code:
<div class="container-client">
<form action="#">
<div class="user-details">
<div class="input-box">
<span class="details">Collaborateurs<small>*</small></span>
<input type="text" placeholder="Selectionner un collaborateur" list="resource-list" required autocomplete="off" id="candidate">
<datalist id="customer-list">
<option value="Alex">Menuisier</option>
<option value="Peter">Charpentier</option>
<option value="Alain">Ingénieur béton</option>
<option value="Adam">Placo</option>
</datalist>
</div>
<div class="button-plus">
<input type="button" value="+" onClick="addResource();">
</div>
</div>
</form>
<hr>
<form action="index.html">
<div class="user-details">
<div class="input-box">
<span class="details">Mon équipe:</span>
</div>
<div class="new-box" id="dynamic-list">
</div>
<div class="new-box">
<div class="button">
<input type="submit" value="✔">
</div>
</div>
</div>
</form>
</div>
Here below the JS code I tried to use; adding the resource name to the div works completely fine, however the removal of the resource name doesn't work.
function addResource()
{
var new_team_member = document.getElementById ('dynamic-list');
var generic_list = document.getElementById ('resource-list');
var candidate = document.getElementById("candidate");
if (candidate.value =='')
{
alert('No data selected');
}
else
{
var div = document.createElement("div");
div.setAttribute('class','input-box');
var input = document.createElement("input");
input.setAttribute('type','text');
input.setAttribute('placeholder',candidate.value);
input.setAttribute('disabled','disabled');
div.appendChild(input);
new_team_member.appendChild(div);
generic_list.removeChild(candidate);
document.getElementById('candidate').value = '';
}
}
The error message I got is about "add-resources.js:20 Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node." indicating thatt the following JS line is causing the problem: generic_list.removeChild(candidate);
Can you please help recommending a solution. Thanks in advance.
First of all, in the code, you provided the resource-list and customer-list look like they should be the same thing. In the input tag, the customer-list is used, and in the datalist, the resource-list is used. I've guessed that both of these should be resource-list, to link them correctly.
It looks like you are trying to get the datalist item that you clicked. In the code, as it is right now, you are removing the <input> tag as your candidate variable. If you would remove this, the whole input field would be gone, and the error is caused by this input field not being a child of the generic_list variable.
Now to solve this issue, you can use the document.querySelector() function to get the datalist item that was selected. The following change to your code would have the desired effect:
function addResource()
{
var new_team_member = document.getElementById ('dynamic-list');
var generic_list = document.getElementById ('resource-list');
var candidate = document.getElementById("candidate");
if (candidate.value =='')
{
alert('No data selected');
}
else
{
var div = document.createElement("div");
div.setAttribute('class','input-box');
var input = document.createElement("input");
input.setAttribute('type','text');
input.setAttribute('placeholder',candidate.value);
input.setAttribute('disabled','disabled');
div.appendChild(input);
new_team_member.appendChild(div);
// Get datalist item with selected candidate
datalist_item = document.querySelector('#resource-list option[value="'+CSS.escape(candidate.value)+'"]');
// Remove item from list
generic_list.removeChild(datalist_item);
document.getElementById('candidate').value = '';
}
}
This query selector allow you to use CSS like syntax to select elements. In the string '#resource-list option[value="'+CSS.escape(candidate.value)+'"]' it first finds the resource list, and then takes the option tag that has the candidate name as its value.
For security, I also use the CSS.escape() function that makes sure any name with special characters gets correctly escaped in this string.

Capture span value using jquery

Hello Everyone I want to capture price from this span using jquery how can i achieve this please suggest something
<span class="amount"><i class="fa fa-inr"></i>1,000</span>
DropDown:
<li class="tmcp-field-wrap">
<label for="tmcp_select_1">Select</label>
<select class="tmcp-field support-layer-firmness tm-epo-field tmcp-select tm-valid" name="tmcp_select_0">
<option value="Select Firmness_0" class="tc-multiple-option tc-select-option" data-price="">Select Firmness</option>
<option value="Soft_1" class="tc-multiple-option tc-select-option" data-price="1000">Soft</option>
<option value="Medium_2" class="tc-multiple-option tc-select-option" data-price="1500">Medium</option>
<option value="Hard_3" class="tc-multiple-option tc-select-option" data-price="2000">Hard</option>
</select>
<span class="price tc-price hidden">
<span class="amount"><i class="fa fa-inr"></i>1,000</span>
</span>
Now i want to get value using onchange event
I have tried so far
$(".support-layer-firmness .tc-price span").on("change", function() {
var price = $('span.amount').text();
alert(price);
});
You can capture the text by using jquery Class Selector
$('span.amount').text(); // output 1,000
Class Selector: Selects all elements with the given class. Reference
As per comment if you want to get the same span value onChange event then try this.
Method 1
$('select').on('change', function() {
$('span.amount').text();
});
Method 2
You can use also class for selecting the select element
$('select.tmcp-field').on('change', function() {
$('span.amount').text();
});
use jquery selector using class name
$(".amount").text();
https://jsfiddle.net/mc7h22f7/
Please check this demo
You can easily get span value as follow.
On Change you can do something like this
$('.tmcp-select').on('change', function (e) {
alert($('span.amount').text());
});
OnChange Example

jQuery how to dynamically add select element and reset choice?

I am writing a dynamic form in the Play Framework, but I'm not very experienced with javascript. I'm trying to build off of this jQuery example that allows the dynamic addition of fields. Instead of adding only a text field, I want to add a text field and a select box each time. The tricky part is that even if there is a selected item, I want the dynamically added select box to be reset.
Here is my attempt to do this, using this answer
$('.multi-field-wrapper').each(function() {
var $wrapper=$('.multi-fields', this);
$(".add-field", $(this)).click(function(e) {
var obj=$('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
// This following line is incorrect...
obj.find('.blank').prop('selected', true).end().trigger('chosen:updated');
}
);
$('.multi-field .remove-field',
$wrapper).click(function() {
if ($('.multi-field', $wrapper).length > 1) $(this).parent('.multi-field').remove();
}
);
}
);
<form role="form" action="/wohoo" method="POST">
<label>Stuff</label>
<div class="multi-field-wrapper">
<div class="multi-fields">
<div class="multi-field">
<div>
<input type="text" name="stuff[]"/>
</div>
<div>
<select>
<option class="blank" value="">Select a car</option>
<option value="saab">Saab</option>
<option value="mercedes" selected>Mercedes</option>
<option value="audi">Audi</option>
</select>
</div>
<button type="button" class="remove-field">Remove</button>
</div>
</div>
<button type="button" class="add-field">Add field</button>
</div>
</form>
Since it uses the clone() function, if "Mercedes" is selected, then dynamically added select dropdowns will also have "Mercedes" selected. How can I make the new selects display the blank choice?
Thanks!
EDIT - updated my code to reflect the fact that my input and select tags are encapsulated by divs
The "obj" variable becomes the input node selected in the end of this expression:
var obj = $('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
But you should do the trick with select node, in your case it is "obj"`s sibling.
obj.siblings('select').find('.blank').prop('selected', true).end().trigger('chosen:updated');});
http://jsfiddle.net/xogeufa2/1/
Also, if "input" and "select" nodes are enveloped in div tags, they loose their sibling relations. So in this case, you should find another way, to get the "select". For example, through parents:
obj.closest('.multi-field').find('select').find('.blank').prop('selected', true).end().trigger('chosen:updated');
});
http://jsfiddle.net/2ymd7ug7/2/
You just needs to remove the attribute selected from the option tag.
For that you can use removeAttr method
Here is the complete code that does what you described.
$('.multi-field-wrapper').each(function() {
var $wrapper = $('.multi-fields', this);
$(".add-field", $(this)).click(function(e) {
var obj = $('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').end().find('option').removeAttr('selected').focus();
});
$('.multi-field .remove-field', $wrapper).click(function() {
if ($('.multi-field', $wrapper).length > 1)
$(this).parent('.multi-field').remove();
});
});
Just added .end().find('option').removeAttr('selected') to your code :)
I hope I helped..
Find the code here : https://jsfiddle.net/yrchyndk/

Using Javascript to create element, then assign onclick to call pikadate

First time poster, long time forager. I have a system I am developing, cleaning up the process I would like to use pikaday.js to help users select the date insted of typing it in by hand.
The process:
From a dropdown (HTML) element, call to handleSelection(choice). handleSelection then looks at the option selected and either creates an input or a second select element with options. For two of the options I would like to create an input and add an onclick to kick pikadate...All I am getting is a input field with no call to the function on click, I can type in the date in the correct format and get a result so the post portion is working.
See code as follows:
JavaScript protion:
<script src='moment.js></script> <----used for date format only
<script src='pikaday.js></script>
<script>
function handleSelection(choice)
{
if(choice=='ordnum' || choice=='po' || choice=='serial' || choice=='asset') <----Works as intended
{
var a=document.getElementById('input');
var input=document.createElement('input');
input.type='text';
input.name='value';
a.appendChild(input);
}
if(choice=='varified')<----Works as intended
{
var a=document.getElementById('valid');
var valid=document.createElement('select');
valid.name='value';
valid.innerHTML="<option value='y'>Validated</option><option value='n'>Not Validated</option>";
a.appendChild(valid);
}
if(choice=='loc')<----Works as intended
{
var a=document.getElementById('valid');
var valid=document.createElement('select');
valid.name='value';
valid.innerHTML="<option value='loc0'>loc0</option><option value='loc1'>loc1</option><option value='loc2'>loc2</options><option value='loc3'>loc3</option><option value='loc4'>loc4</option><option value=';loc5'>loc5</option>";
a.appendChild(valid);
}
if(choice=='drcv' || choice=='disrv') <---Isn't working as intended!
{
var a=document.getElementById('input');
var input=document.createElement('input');
input.type='text';
input.name='value';
input.id='pkr';
input.onclick='getDate()'; <----Tried with quotes and with out, will not call out to getDate()
a.appendChild(input);
}
}
<script>
function getDate()
{
var picker = new Pikaday({field:docuemnt.getElementById('pkr'),format:'YYYYMMDD'});
</script>
}
}
</script>
HTML portion:
<body>
<form class='container' name='report' action='somepage' method='post'>
<select id='select' onChange='handleSelection(value)' name='opt'>
<option value="ordnum">Order Number</option>
<option value="po">Po Number</option>
<option value="drecv">Date Received</option>
<option value="disrv">Date In Service</option>
<option value='serial'>Serial Number</option>
<option value='asset'>Asset Tag</option>
<option value='loc'>Location</option>
<option value='varified'>Verified</option>
<option value='*' selected>All Systems</option>
</select>
<input type="submit" name="submit" value="Fetch..">
</p>
<p id='input'>
</p>
<p id='valid'>
</p>
</form>
</body>
</div>
</html>
Replace
input.onclick='getDate()';
with
input.addEventListener('click', getDate, false);
you could also use input.onclick = getDate;, but addEventListener is the preferred way of adding event listeners.
And make sure the getDate function is in scope, that means that it's either inside the same script tag as the event listener, or a script tag above the one containing the event listener.
Hoisting doesn't help across script tags.
So playing around a bit, seems style was the issue. I had a div style set in my original CSS and it seems that the div in the pikaday.css was going off of that position causing the stretched effect. I adjusted the percentage of the div in pickaday.css to 55% and now have the full effect that was wanted.

Change text of all elements with specific data-attribute

I'm currently trying to use jQuery to change the text of a number of elements to the value of a specific data-attribute.
For example:
index.html
----------
<h1 data-change="text2">text1</h1>
<p data-change="paragraph2">paragraph1</p>
I want to change 'text1' to 'text2' and 'paragraph1' to 'paragraph2' (the value of data-change for that specific element).
How would I go about doing this?
I assumed I would be able to 'select' all of the elements with the data-attribute 'data-change' and then just do a simple $(this).text($(this).data('change')); or something.
You can do this:
$('[data-change]').each(function(){
$(this).text($(this).data('change'));
});
You can iterate over the elements and change its text.
.text method could accept a callback function.
$('[data-change]').text(function() {
return $(this).data('change');
});
How would you like this~
-html-
<select id="" name="" class="input_select">
<option value="text2" selected="selected">text2</option>
<option value="paragraph2">paragraph2</option>
</select>
<h1 class="text2">text1</h1>
<p class="paragraph2">paragraph1</p>
</pre>
-js-
$(document).ready(function(){
$('.input_select').change(function(){
var valitem = $(this).val()
if (valitem == 'text2')
{
$('.text2').text(valitem)
}else{
$('.paragraph2').text(valitem)
}
})
});

Categories