Programmatically set select (multiple) element value - javascript

I want to populate a select field with onclick but i don't know how to filter the array to only the value of the clicked button. With my code all the array objects populate the input and I want only the value of the clicked button to populate the input. Any hints?
<input type="hidden" id="id_user" value="{{user.id}}">
<select id="id_entities" class="js-example-programmatic" style="width:100%" multiple="multiple">
{% for teu in tagEntityUsers %}
<option value="{{teu.entity_id}}" class="js-programmatic-set-val">{{teu.entity}}</option>
{% endfor %}
</select>
{% for teu in tagEntityUsers %}
<tr>
<td>{{teu.entity}}</td>
<td>{{teu.user}}</td>
<td><button id ="{{teu.entity_id}}" class="js-programmatic-set-val" value="{{teu.entity_id}}" onclick="populate_box(this.id)">add entity</button></td>
</tr>
{% endfor %}
<script>
var $example = $(".js-example-programmatic");
var arr = $.map($('.js-programmatic-set-val'), function (el) { return el.value; });
function populate_box() {
$example.val(this.arr).trigger("change"); }
</script>

I'll add a prefix to button id and set jQuery listener to it:
$("button[id^='prefix_']").click(function(){
value = $(this).attr('data-value');
$('#id_entities option[value="' + value + '"]').prop("selected", true).change();
});
So, the button will be:
<button id="prefix_{{teu.entity_id}}" class="js-programmatic-set-val" data-value="{{teu.entity_id}}">add entity</button>
UPD: Code above is fixed, see it in action. And I highly recommend to change value attribute on button to data-value, read more about data-* attributes

Related

Dynamic querySelector with Dynamic Jinja HTML

I have forms that are rendered dynamically based on values in a dictionary. They are given an ID based on the key value. They are all initially hidden.
<div id="subforms" style="display: none" >
{%for k, v in options.items() %}
<h3>{{k}}:</h3>
<form id= "{{k}}">
{% for option in v %}
<label>{{option}}</label>
<input type="checkbox" name="{{option}}_enabled">
{% endfor %}
</form>
{% endfor %}
</div>
I now create an input list with those same keys:
<form action="/action_page.php">
<input list="tables" id="tablelist" >
<datalist id="tables">
{% for key in options.keys() %}
<option value={{key}}>
{% endfor %}
</datalist>
</form>
Last I have Javascript used to listen to the tablelist element and select a form based on the inputlist's value.
const tables = document.getElementById("tablelist")
const subform_block = document.getElementById("subform_display")
const forms = document.getElementById("subforms")
tables.oninput = () => {
let form =
forms.querySelector('form[id="${tables.value}"]');
if(form){
subform_block.innerHTML = form.outerHTML;
}
else {
subform_block.innerHTML = "not found";
}
}
The querySelector is not working. I confirmed that the HTML is rendered correctly and the IDs are consistent, but my querySelector is unable to find any of the forms. What is wrong?
Changed:
let form = forms.querySelector('form[id="${tables.value}"]');
to:
document.querySelector('form[id=' + tables.value + ']');
And it works. Not sure why ${tables.value} wasn't recognized properly

How to differentiate and club together multiple select dropdowns?

I have a table with multiple rows, and 4 columns. Each column contains a select dropdown, the options in the second column depends on the selection of first one, third one depends on second one and so on. I tried giving ids to selects and implementing onclick listeners. but it works only for the first row. Please help me solve this.
Here's the HTML code:`
<table>
{% for int i in (0,x) %}
<tr>
<td>
<select id='Product'>
<option>Car</option>
<option>Bike</option>
<option>Bus</option>
</td>
<td>
<select id='Model'>
</td>
<td>
<select id='Make'>
</td>
<td>
<select id='Color'>
</td>
</tr>
{% endfor%}
Here's the Jquery:
$("#product").change(function (event) {
event.preventDefault();
var val = $(this).val();
if( val == "none"){
$('#Model').empty().append($("<option></option>")
.attr("value","none")
.text("Select"));
$('#Make').empty().append($("<option></option>")
.attr("value","none")
.text("Select"));
$('#Color').val("Red");
}else{
var url_select = "/XYZ/product/?selected_product=" + val;
$(".innerload").css("visibility", "visible");
$.get(url_select, function(data){
$('#Model').empty().append($("<option></option>")
.attr("value","none")
.text("Select"));
$('#Make').empty().append($("<option></option>")
.attr("value","none")
.text("Select"));
$.each(data, function (i, item) {
$('#Model')
.append($("<option></option>")
.attr("value",item.model)
.text(item.model));
});
});
}
});
Similar jqueries for Model and Make onChange.
Please do not use same id in multiple time in loop id same for all time that's way it's not work

jquery incorrect first text field value

I have a popup. It has three text input fields. All of them have some values that have been set up via another form. The second and third fields have the correct value when I focus on them.
On focusing on the first field, I don't get the content as expected. I have used html() function of jquery to display the content in these text input fields.
A screenshot is here:
A snippet of my ready function is here:
$(document).ready(function(){
$( "body" ).delegate( ".editDiv", "click", function() {
changed_id = this.id
var copyData = $("#" + changed_id).html();
var changed_class = "edit";
var new_input = "<input id=" + changed_id + " " + "class=" + changed_class + ">";
var editableText = $(new_input);
editableText.val(copyData);
$(this).replaceWith(editableText);
editableText.focus(function() { $(this).select(); });
});
The same code returns correct values for 2nd and 3rd fields. But it is not so for the first field. What could be the possible reason?
Edit
The HTML code for the popup is:
<div id="dialog-form" title="Add advance">
<h4>
<b>
{{ full_name }}
</b>
<span>
<small>
{{ month_name }} {{ year }}
</small>
</span>
</h4>
<table id="special" class="table" style="width: 70%; margin: auto;">
<tbody>
{% for a in old_advances %}
<tr>
<td class="text-right popup">
<span style="float:left;"> {{ a.advance_date }} </span>
<div class="editDiv" id="{{a.id}}">{{ a.advance_amount|floatformat:2 }}
</td>
</tr>
{% empty %}
<p> No advance given this month.</p>
{% endfor %}
</tbody>
</table>
</div>
</div>
You should use the val to get the value of input(textbox, checkbox, etc.).
var copyData = $.trim($("#" + changed_id).val());
To get the value of select dropdown:
var copyData = $.trim($("#" + changed_id +" option:selected").val());
OR
If you want to get the inner text(div, span, etc.) use text:
var copyData = $.trim($("#" + changed_id).text());
You might also want to trim it to remove extra spaces at the beginning and end of the string.

Getting post data from html table inside a form? Django

I have a dynamically populated html table that can be edited by an user (they can add rows delete them, etc -this is managed through javascript-).
The problem is, even when the table is inside the form, the server doesn't get any post data from it.
Here is the code for the template:
{% extends 'base.html' %}
{% block content %}
<script>
function add_row(){
var table = document.getElementById("body");
var row = table.insertRow(table.rows + 1);
var cell = row.insertCell(0);
var combo1 = document.createElement("select");
var option;
{% for opt in options_all %}
option = document.createElement("option");
option.setAttribute("value", "{{ opt.id }}");
option.text="{{ opt.description }}";
combo1.add(opcion);
{% endfor %}
cell.appendChild(combo1);
}
</script>
<form action='.' method='post'>
{% csrf_token %}
{{ form.as_p }}
<input type="button" value="New row" onclick="add_row()">
<table id="table_id">
<thead>
<tr>
<th>
Options
</th>
</tr>
</thead>
<tbody id="body">
</tbody>
</table>
<input type='submit' value='Submit'>
</form>
{% endblock %}
How can I get the data from the select elements?? Thanks!!
Edit: I have checked the request element and request.post doesn't have the desired data
SOLVED.
You have to specify a name for each select element inside the table. (Not the option elements)

Show button in Django template only when the file is selected through check box?

I am getting the check box dynamically in Django template like this:
<td><input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /></td>
<td><label for="choice{{ forloop.counter }}">{{ choice.file_name }}</label></td>
There's a unshare button like this:
<button>Unshare</button>
I want to show the Unshare button only when the user clicks on check-box.
Firstly add some more id's to your template so that you can identify elements.
<table id="choices">
{% for choice in choices %}
<td><input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /></td>
<td><label for="choice{{ forloop.counter }}">{{ choice.file_name }}</label></td>
{% endfor %}
</table>
Then give the button an id and an inline style -
<button id="unshare_button" style="display: none;">Unshare</button>
Then use the following javascript (this shows the button as soon as any one of the
checkboxes is clicked - it doesn't hide the button if they're unchecked).
var choices_table = document.getElementByID('choices');
var checkboxes = choices_table.getElementsByTagName('input');
var unshare_button = document.getElementByID('unshare_button');
for (var i = checkboxes.length; i > 0; i--) {
checkboxes[i].addEventListener('click', function() {
unshare_button.style.display = 'inline';
}
}
I'm afraid I haven't checked this code, but it should give you an idea.

Categories

Resources