<div class="uk-sortable js-sortable-option">
<div class="uk-margin-small-top">
<i class="uk-icon-bars"></i>
<input type="text" name="customfield[data][option][0]" value="First Option">
</div>
<div class="uk-margin-small-top">
<i class="uk-icon-bars"></i>
<input type="text" name="customfield[data][option][1]" value="Second Option">
</div>
<div class="uk-margin-small-top">
<i class="uk-icon-bars"></i>
<input type="text" name="customfield[data][option][2]" value="Third Option">
</div>
</div>
<button class="uk-margin-small-top uk-button js-add-item" type="button">Add Item</button>
In this form, a user can create a simple list, which can be used, e.g. for a custom select input. Every item have a unique id customfield[data][option][id]. To add a item, the user can click the button.
My problem is, that I have to change the name attribute for every new added item. How can I only change the id of the name-attribte?
var sortele = $('.js-sortable-option'),
additem = $('.js-add-item');
additem.on('click',function(){
ele = sortele.first();
/** code to change name attr (e.g. to customfield[data][option][newid])*/
sortele.append(ele);
});
to change any attribute of an element , use :
$(elm).attr("attr_name","new_val");
in this case , you should have a counter variable for using as array index.
var counter = 0;
additem.on('click',function(){
ele = sortele.first();
ele.attr("name", "customfield[data][option]["+counter+"]");
counter++;
sortele.append(ele);
});
With jquery you can do this:
var sortele = $('.js-sortable-option'),
additem = $('.js-add-item');
additem.on('click',function(){
ele = sortele.first();
myVar = "something";
/** code to change name attr (what to do?)*/
ele.attr("name", myVar);
});
Related
I need to reset only the form fields that are changed (reset to previous value).
I tried to use the reset but it completely resets the entire form and I don't need this.
How can I do this?
function clearResult() {
document.getElementById("save").reset();
}
<div class = "container">
<form method="post" id="save" onload="onLoad()">
<div class="field">
<label for="id"> ID:</label>
<input type="number" id="id" name="id" />
</div>
<div class="field">
<label for="type"> Fragment Type: </label>
<input type="text" id="type" name="type" />
</div>
<div class="button">
<button type="submit" class="full">Save changes</button>
<input type="button" value="Cancel" onclick="clearResult()" />
</div>
</form>
</div>
First of all you should to store the predefined values of form elements to set them back when you want to reset them back.
Then you can use this globally defined initial values to set them back whnever reset event occurs.
var id, type;
const form = document.getElementById('save');
document.onload = (event) => {
id = form.id.value;
type = form.type.value;
};
function clearResult() {
form.id.value = id;
form.type.value = type;
};
It was simple. When page load just get values from that fields.
Make with document.onload:
var firstValue = document.getElementById("yourFieldId").value;
After form submit get values like below:
var currentValue = document.getElementById("yourFieldId").value;
And after submit in reset check if CURRENT VALUES equal with VALUES FROM FIRST TIME
Example
if(firstValue != currentValue){
document.getElementById("yourFieldId").value = firstValue;
}
Good Day Friends. I have a problem... Thanks, if you help me
I have a couple of inputs into a div. I copied that div with Clone function in java script (by click a button) and right now, I have two divs. but my problem:
1- I don't know, How can I get the values of inputs correctly (the input's names are the same)?
2- and I have a select input in div, that some inputs add or remove by choose each option of select input. Now after copied div, choose one option in div2, create changes in div1... and I don't want it !!
<div class="levels">
<div class="add_senario_level">
<span>Level 1</span>
<form>
<select name="condition" onchange="show_div(this,'shop during');">
<option selected="selected" disabled="disabled">choose condition</option>
<option>shop after registration</option>
<option>shop during</option>
</select>
<div id="shop_during" style="display:none;">
<input type="number" id="shop_during_num" name="shop_during_num" placeholder="Enter number">
<select id="shop_during_time" name="shop_during_time">
<option selected="selected">hour after registeration</option>
<option>day after registeration</option>
<option>week after registeration</option>
<option>month after registeration</option>
</select>
</div>
<div>
<button type="button" class="newLevel"> Add New Level </button>
</div>
</form>
</div>
</div>
<script>
$(document).ready(function()
{
$(".newLevel").click(function()
{
$(".add_senario_level").clone().appendTo(".levels");
});
});
function show_div(obj, id)
{
txt = obj.options[obj.selectedIndex].text;
if (txt.match(id))
{
document.getElementById("shop_during").style.display = 'block';
}
else
{
document.getElementById("shop_during").style.display = 'none';
}
}
</script>
You can use jQuery's find function to find a child element and the attr function to get and set attribute values. You will want to do this to change on the id and name attributes for the input and select like below:
HTML
<input type="number" id="shop_during_num0" name="shop_during_num0" class="shop_input" placeholder="Enter number">
JavaScript
$(".newLevel").click(function()
{
const count = $('.add_senario_level').length;
const clone = $(`#add_senario_level${count - 1}`).clone();
const input = clone.find(`#shop_during_num${count - 1}`);
const select = clone.find(`#shop_during_time${count - 1}`);
input.attr('name', `shop_during_num${count}`);
input.attr('id', `shop_during_num${count}`);
select.attr('name', `shop_during_time${count}`);
select.attr('id', `shop_during_time${count}`);
clone.appendTo(".levels");
});
In the show_div method, you can use $(obj) to reference the select that called the function and show or hide the correct element with
$(obj).parent().find('#shop_during').css('display', 'block');
I'm not really sure the best way to go about this but I've laid the framework.
Basically, I would like to add the functionality so that when my #moreItems_add button is clicked and calls the moreItems function, I simply want to add a new Input field below it, and so on. I want to limit this to 10 fields though, so I show that in the function.
The only trick is, I will be submitting all fields via ajax to save to the database, so I need to try and keep track of an ID with each.
What's the best way to continue the javascript here so that I can append an input field on button press and keep track of IDs for each?
<div class="modal-body">
<form id="Items">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]">
<button id="moreItems_add" onclick="moreItems()" id="moreItems">More Items</button>
</form>
</div>
<div class="modal-footer">
<input type="submit" name="saveItems" value="Save Items">
</div>
<!-- modal JS -->
<script type="text/javascript">
function moreItems(){
var MaxItems = 10;
//If less than 10, add another input field
}
</script>
You can use the jQuery .insertBefore() method to insert elements right before "more items" button. Below is the code representing this:
var maxItems = 1;
function moreItems() {
if (maxItems < 10) {
var label = document.createElement("label");
label.id="ItemLabel"+maxItems;
label.innerHTML = "Item "+(maxItems+1)+": ";
var input = document.createElement("input");
input.type='text';
input.name = 'item'+maxItems;
$('<br/>').insertBefore("#moreItems_add");
$(label).insertBefore("#moreItems_add");
$(input).insertBefore("#moreItems_add");
maxItems++;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-body">
<form id="Items">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]">
<button type="button" id="moreItems_add" onclick="moreItems()" id="moreItems">More Items</button>
</form>
</div>
<div class="modal-footer">
<input type="submit" name="saveItems" value="Save Items">
</div>
Something like this should do the trick:
<!-- modal JS -->
<script type="text/javascript">
var MAX_ITEMS = 10,
added = 0;
function moreItems(){
if (added >= MAX_ITEMS) return;
var newField = document.createElement('input');
newField.type = 'text';
// TODO: Any field setup.
document.getElementById('items').appendChild(newField);
added++;
}
</script>
In terms of tracking each field with an ID, that should always be done by the back-end for data integrity and safety reasons.
some years ago I've wrote an article about making a repeated section using jQuery.
The live example is available on jsFiddle.
In the example you can find that both "add" and "remove" button are available, however you can set just the "add" button for your purpose.
The idea to limit to specific number of repeated boxes is to watch the number of repeatable elements just created in the context. The part of code to change in the live example is rows 13-18:
// Cloning the container with events
var clonedSection = $(theContainer).clone(true);
// And appending it just after the current container
$(clonedSection).insertAfter(theContainer);
There you should check if the number of repeated elements is less than <your desired number> then you will allow the item to be created, else you can do something else (like notice the user about limit reached).
Try this:
const maxItens = 10,
let itensCount = 0;
function moreItems() {
if (itensCount++ >= maxItens) {
return false;
}
let newInput = document.createElement('input');
// use the iterator to make an unique id and name (to submit multiples)
newInput.id = `Items[${itensCount}]`;
newInput.name = `Items[${itensCount}]`;
document.getElementById('items').appendChild(newInput);
return false;
}
Add type "button" to stop submiting the page (also, your button have two ID):
<button id="moreItems_add" onclick="moreItems();" type="button">More Items</button>
The submit button must be inside the form to work:
<form>
<div class="modal-body">
<div id="Items">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]">
</div>
<button id="moreItems_add" onclick="moreItems()" id="moreItems">More Items</button>
</div>
<div class="modal-footer">
<button type="submit">Save Items</button>
</div>
</form>
To append itens in sequence the button must be outside of div "itens".
I have the following label:
<div id="email">
<label>
myemail#gmail.com
</label>
<i class="fa fa-edit"></i>
</div>
<div id="phone">
<label>
1234567890
</label>
<i class="fa fa-edit"></i>
</div>
When I click on the edit button I want to replace the label with an input and set the label value as selected. Below is what i have tried so far:
$('.fa-edit').click(function(){
var info = $(this).closest('div');
var label = info.find('label');
var curr_value = label.text();
label.replaceWith('<input class="edit_input" type="text" value="'+curr_value+'" />')
.focus(function(){
//alert(this);
this.select();
});
// some code ..
the problem is that I can not set the input text as selected (ready to be replaced).
What should I do?
Create the input element and set the focus & select on it after you replace the label.
Please check the below code:
$("#editBtn").click(function(){
var label = $(this).parent().find('label');
var curr_value = label.text().trim();
var newInput = $('<input class="edit_input" type="text" value="'+curr_value+'" />')
label.replaceWith(newInput)
newInput.focus().select()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="email">
<label>
myemail#gmail.com
</label>
<button id="editBtn">EDIT</button>
</div>
the value returned from .replaceWith is still the old <label /> reference, you need to re-select the input, so that you can focus it.
label.replaceWith('<input class="edit_input" type="text" value="'+curr_value+'" />')
$('.edit_input').off('focus').on('focus',function() {
this.select()
}).trigger('focus')
use off() to remove previous event listener everytime the user click the edit button again.
i hope that help you.
var label = $('label');
var curr_value = label.text();
label.replaceWith('<input class="edit_input" type="text" value="'+curr_value+'" />').focus(function(){
$(this).select(); });
I basically on click need to insert the data- into a form. The issue is that both forms use the same element classes and when I perform one function it inserts the data but as soon as I click to run the other function it clears the original data. Here is my code:
HTML
<div class="inbox-widget nicescroll mx-box">
<a data-dismiss="modal" data-toggle="modal" href="#con-close-modal">
<div class="inbox-item" data-tag="Followers" data-social_type="twitter">
<p class="inbox-item-date">Click to add</p>
</div>
<div class="inbox-item" data-tag="Friends" data-social_type="twitter">
<p class="inbox-item-date">Click to add</p>
</div>
</a>
<a data-dismiss="modal" data-toggle="modal" href="#con-close-modal">
<div class="inbox-item2" id="chosen_account" data-social_id="12345">
<p class="inbox-item2-date">Click to add social ID</p>
</div>
</a>
<a data-dismiss="modal" data-toggle="modal" href="#con-close-modal">
<div class="inbox-item" id="chosen_account" data-social_id="6789">
<p class="inbox-item-date">Click to add social ID</p>
</div>
</a>
</div>
<form>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="input" id="social_id" type="text" name="social_id" />
<input type="input" id="social_type" type="text" name="social_type" />
<input type="input" id="chart_type" type="text" name="chart_type" value="line"/>
<input type="input" id="chart_tag" type="text" name="chart_tag"/>
</form>
My Jquery:
$('.inbox-item').click(function() {
var social_type_value = $(this).data('social_type');
var social_type_input = $('#social_type');
social_type_input.val(social_type_value);
var chart_tag_value = $(this).data('tag');
var chart_tag_input = $('#chart_tag');
chart_tag_input.val(chart_tag_value);
var social_id_value = $(this).data('social_id');
var social_id_input = $('#social_id');
social_id_input.val(social_id_value);
});
I also created a fiddle to show whats happening: https://jsfiddle.net/p18f3dow/1/
if i got your problem right, you'd want to use one function - but depending on the clicked element add different data... but don't overwrite the already entered data, when clicked element don't contains relevant data...
why not checking, if the data tag exists, in the first place:
$('.inbox-item').click(function() {
if ($(this).data('social_type')) {
var social_type_value = $(this).data('social_type');
var social_type_input = $('#social_type');
social_type_input.val(social_type_value);
}
if ($(this).data('tag')) {
var chart_tag_value = $(this).data('tag');
var chart_tag_input = $('#chart_tag');
chart_tag_input.val(chart_tag_value);
}
if ($(this).data('social_id')) {
var social_id_value = $(this).data('social_id');
var social_id_input = $('#social_id');
social_id_input.val(social_id_value);
}
});
this would be the quick and dirty solution, though.
better one would be like storing the complete clicked data objects and iterating through them, filling the correct fields. see https://jsfiddle.net/p18f3dow/4/
therefore you have to ensure that the part behing the data- in your html always matches your id in the form. (had to change it from data-tag to data-chart_tag)
then all you need is a simple function like that:
$('.inbox-item').click(function() { //when clicked
var stored_data = $(this).data(); //save everything in an object
for (var key in stored_data) { //iterate through the object
if (stored_data.hasOwnProperty(key)) {
$('#' + key).val(stored_data[key]) //create an id with #+key and insert the value
}
}
});