javascript function only works for first input box in example - javascript

I'm echoing rows of $data inside input boxes. The javascript function below copies the input value to the clipboard upon clicking the input box. The problem is the function only works for the first input box and not subsequent echoed ones. I think I need to assign a unique id to each input box and I'm not sure how to do this.
// for each row it is echoing the following:
echo '<input id="copy-text" type="text" value="'.$data.'" size="50">';
<script>
document.getElementById("copy-text").onclick = function() {
this.select();
document.execCommand('copy');
}
</script>

ID should always be unique. When you have multiple IDs with same value javascript looks for the first match with that id and skips the rest.
If you are looping through each row, use an index like this
echo '<input id="copy-text_'.$i'" type="text" value="'.$data.'" size="50" onclick="copy($i)">';
<script>
function copy(index) {
var elem = document.getElementById("copy-text_" + index);
elem.select();
document.execCommand('copy');
}
</script>

Give the elements a class:
echo '<input class="copy-text" type="text" value="'.$data.'" size="50">';
And have a single script tag that finds all those elements and binds the event handler to them:
function handler() {
this.select();
document.execCommand('copy');
}
Array.from(document.querySelectorAll('.copy-text'))
.forEach(function(element) {
element.addEventListener(handler);
});

Related

Unable to get element id dynamically in javascript

I have a list of students that I am looping through and adding to my page. Each student has a unique ID, and when getStudentInfo is invoked, it does something with the id. The problem is that whichever student I click, I get back the same id, belonging to student1.
Where am I going wrong?
foreach ($students as $student) {
echo '<tr>';
echo '<td>
'.$student[student_permalink].'
<input type="submit"
value="info"
onclick="getStudentInfo()"
class="student-name-btn"
id="'.$student[student_permalink].'"
/>
</td>';
}
js:
function getStudentInfo() {
var studentLink = $('.student-name-btn').attr('id');
console.log(studentLink);
}
Your code is selecting all the buttons on the page with that class and than reads the id of the first one in the list. You are not limiting it to the one that was clicked.
What most people would do is add events with jQuery and not inline.
//needs to be loaded after the element or document ready
$(".student-name-btn").on("click", function() {
console.log(this.id);
});
For yours to work, you would need to pass a reference to the button that was clicked.
onclick="getStudentInfo(this)"
and than change it to use the node passed in
function getStudentInfo(btn) {
var studentLink = $(btn).attr('id');
console.log(studentLink);
}
You can pass the reference to the element being clicked on the onclick event
foreach ($students as $student) {
echo '<tr>';
echo '<td>
'.$student[student_permalink].'
<input type="submit"
value="info"
onclick="getStudentInfo(this)" // << added this which refers to the input
class="student-name-btn"
id="'.$student[student_permalink].'"
/>
</td>';
}
And then use that to fetch the id in the js
function getStudentInfo(el) {
var studentLink = $(el).attr('id');
console.log(studentLink);
}
Don't use inline events - there's no need to clutter up the HTML with that. You have a common class on your element, so just make a jQuery handler and use an instance of this
$('.student-name-btn').click(function() {
var id = this.id;
});
Like #epascarello alluded to, you are not selecting the button that was actually clicked. What you should do is have your event handling in your JS, not in the HTML so you can see better how it works and use the this keyword within the closure to reference the clicked button.
$(document).on('click', '.student-name-btn', function(evt) {
// Prevent default if trying to do your own logic
evt.preventDefault();
// Need to use the "this" keyword to reference the clicked element
var studentId = $(this).attr('id');
console.log(studentId);
});
You can do this without inline JavaScript and since you're using jQuery drop the onClick() and the form element:
echo '<tr>';
echo '<td id="'.$student['student_permalink'].'" >
'.$student['student_permalink'].'
</td>';
You also need to quote the identifier in the array variable, 'student_permalink'.
The jQuery will be this:
$('td').click(function() {
var studentLink = this.id;
console.log(studentLink);
});

How to get the value of text box using onChange function

I want to get a value of text box when it's value chenaged. I am using onchange function to get the value of text box when it changed.Here it's give a result but not changed value.It give's a value of the text box before changed value.How can get changed value.
Here is my script:
function myFunction(id)
{
var id=id;
var quantity = document.getElementById("quantity").value;
alert(quantity);
}
My onchange function:
<input type="text" value="<?php echo $res['quantity']; ?>" name="qty" id="quantity" onChange="myFunction(<?php echo $res['id']; ?>);"/>
Thanks in advance.
For <input> tag you have oninput event, not onchange. Your Javascript should look like this:
document.querySelector('#quantity').addEventListener('input', myFunction);
function myFunction() {
// 'this' refers to the input, because you appended listener to it
console.log(this.value); //to avoid alert spam...
}
Functions gets hoisted so you can use them before they are declared, in case you were wondering.
Another way to add listener (but beware, you can replace or override it if you perform assignment again:
document.querySelector('#quantity').oninput = myFunction;
And your HTML would look like this:
<input type='text' id='quantity' name='qty' value="<?php echo $res['quantity']; ?>">
Use OnKeyUp or blur Event so once you enter text and switch to something from that text box you will get that text use alert to have a check:
<input type="text" onBlur="check(this.value);" />
Function check(id) {
alert(id);
}
hope it will help...

How to dynamically remove input field which is created dynamically using JavaScript

I created an input text dynamically using JS, but what if I want to remove the input field one by one dynamically using a button by calling "removeTextField()" from the JS?
Here is the JS:
<script type="text/javascript">
function addTextField(){
var element = document.createElement("input");
element.setAttribute("name", "i[]");
element.setAttribute("value", "");
element.setAttribute("class", "daters");
element.setAttribute("id", "timepicker_7");
var myvalue = document.getElementById("dispTime");
myvalue.appendChild(element);
}
</script>
...
<input type = "button" class="button2" value = "Add Time" onclick = "addTextField()"/>
The way you create the elements has a problem. You are giving the new element a hardcoded id and this means that when adding more than one, you will end with multiple elements with the same id ?(which is invalid and prone to errors when accessing the DOM)
Since you use jQuery, why not simplify your code when adding/removing elements by utilizing it?
I would use something like this
html
<input type="button" class="button2 addField" value="Add Time" />
<input type="button" class="button2 removeField" value="Remove Time" />
script
$(function(){
$('.addField').on('click', function(){
$('<input type="text">', {
name: 'i[]',
value: '',
'class': 'daters'
}).appendTo('#dispTime');
});
$('.removeField').on('click', function(){
$('#dispTime .daters').last().remove();
});
});
If you are not using jQuery then the way to remove an element
function removeTextField(){
var elements = document.getElementById('dispTime').getElementByClassName('i[]'),
last = elements[elements.length-1];
last.parentNode.removeChild(last);
}
function removeTextField() {
var timepicker = document.getElementByID("timepicker_7");
timepicker.parentElement.removeChild(timepicker);
}
you can use $.remove() for this..
refer: http://api.jquery.com/remove/
Suggestion: instead of creating elements like the one you did, create like this.
$('body').append("<input name='i[]' value='' class='daters' id='timepicker_7' />");
$('#timepicker_7').remove();
if you are creating elements on demand and want to use this element multiple times.
now you have a function which can be used as many times you want, anywhere on the page
function GetTextField() {
var field = "<input name='i[]' value='' class='daters' id='timepicker_7' />";
return field;
}
var field = GetTextField();
$('body').append(field);
$("#dispTime #timepicker_7").remove()
This is my idea(not tested):
Every time you add an input, just push it in a array, so you can remove it after:
<script type="text/javascript">
var inputStack = new Array();
function addTextField(){
var element = document.createElement("input");
element.setAttribute("name", "i[]");
element.setAttribute("value", "");
element.setAttribute("class", "daters");
element.setAttribute("id", "timepicker_7");
var myvalue = document.getElementById("dispTime");
myvalue.appendChild(element);
inputStack.push(element);
}
// Now if you want to remove, just do this
inputStack[0].remove(); // I think it'll work for example
</script>

JQuery - Append to text area that has been modified with Jquery

I am trying to append the value of a div or a input box to my text area. I have this working no problem but if i clear the contents of the text area first with a Jquery action it doesnt allow me to use my append features.
E.g.
<script type="text/javascript">
$(document).ready(function() {
$("#Column1").click(function () {
$("#sql").append($("#Column1").val())
})
$("#Column2").click(function () {
$("#sql").append($("#Column2").html())
})
$("#reset_sql").click(function () {
$("#sql").val('SELECT ')
})
</script>
<div> <input type="checkbox" name="column1" id="column1" value="`Column1`"> column1 </div>
<div id="Column2"> Column2 </div>
<textarea rows="10" cols="80" name="sql" id="sql"><? echo $sql ;?></textarea>
<input type="submit" value="submit" />
<input type="button" value="reset sql" id="reset_sql" />
The input and div lines above are just generic examples but relate exactly to what i'm trying to do.
I dont understand that when i clear the text area with javascript that my appends wont work. I get no JS errors in firefox error console.
thank you
You have several issues with your code: you haven't closed your document.ready callback, you are using the incorrect case when refering to your ID's, and you're using some of the jQuery methods incorrectly. For example, append() appends HTML to an element, whereas you want to update the value.
Your logic isn't quite correct either, since columns won't be removed when you uncheck a checkbox, and the columns won't be comma delimited (it looks like you are building a SQL string here).
I believe something like this is what you're looking for:
$(document).ready(function() {
var $sql = $('#sql');
var initialValue = $sql.val();
$("#column1, #column2").on('change', function () {
var cols = [];
var checked = $('input[type="checkbox"]').filter(':checked').each(function() {
cols.push($(this).val());
});
$sql.val(initialValue + ' ' + cols.join(', '));
})
$("#reset_sql").on('click', function () {
$sql.val(initialValue)
})
});
Working Demo
Your checkbox has an id of 'column1', but your event handler is $("#Column1").click(function () {.
Case matters! Either change the id to 'Column1' or the event handler to look for $('#column1').
Demo

How to make simplier the jquery code

Aim is to detect if after page load input values are changed.
Input fields (19 fields) for example
<input type="text" name="date_day1" id="date_day1" value=" >
<input type="text" name="date_month1" id="date_month1" value=" >
<input type="text" name="date_year1" id="date_year1" value=" >
<input type="text" name="amount1" id="amount1" value=" >
Then hidden input field like this
<input type="text" name="is_row_changed1" id="is_row_changed1" value="">
<script>
$("#date_day1").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
$("#date_month1").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
</script>
If in any of input fields (19 fields) value is changed, then I need to reflect it in this hidden input field (I decided to set the hidden input field value to 1).
After that ajax with php where I check if the hidden input field value is 1. If 1, then update mysql. Aim is to reduce usage of server resources.
Question
Javascript code for the hidden input field would be long. May be some way (code) to make is shorter (simplier)?
Add a row_changed class to each input then you can target them all with one call:
$(".row_changed").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
(you can also simplify it even more with QuickSilver's comment.)
You could use JQuery selectors in order to set the same "input changed" callback for all input elements declared in your HTML code:
var anyFieldChanged = false; //Global variable
function changedCallBack()
{
anyFieldChanged = true;
alert('Fields changed');
}
allInputs = $('input');
allInputs.each(function() { this.onchange = yourCallBack(); });
I don't know if it's just in your example code, but you have several elements with the same ID, which is not valid. Each ID should be unique (which is the purpose of any ID). You can either add a class to each input you want to track and select on that like Shawn said or if you want to track every input except the hidden on the page you can use
$("input:[type!=hidden]").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
Use like this.
<script>
$("#date_day1").on("change", function () {
$('#is_row_changed1').val(1);
});
$("#date_month1").on("change", function () {
$('#is_row_changed1').val(1);
});
// etc
</script>

Categories

Resources