I'm creating a form inside a foreach loop. What actually I want is that... how can I clear the value of a particular input field on click of an image.
Following is the code which is inside loop. It has many more form fields. But I want to clear a particular input field, because I'm fetching the data from database, making changes and then saving it again.
<a onclick="clearField("<?php echo "field_id".$language["language_id"]; ?>")"
href="javascript:noAction();"><img src="view/image/delete.png">
</a>
<input type="text"
id="<?php echo 'field_id'.$language['language_id']; ?>"
name="file_name[<?php echo $language['language_id']; ?>]"
value="<?php echo isset($document_description[$language['language_id']]) ? $document_description[$language['language_id']]['file'] : ''; ?>"
readonly="readonly"/>
Following is the javascript which is used for above function--
<script>
function clearField(input,val) {
if(input.value == val)
input.value="";
};
</script>
EDITED :- there is one more problem with the following statement --
all quotes which are used inside this statement are not proper. i mean to say that the code do not gets parsed due to some missing or some additional quotes. So please tell me how to correct this.
<a onclick="clearField("<?php echo "field_id".$language["language_id"]; ?>")"
href="javascript:noAction();"><img src="view/image/delete.png">
</a>
You can do this very easily in javascript
HTML code
<img src="http://www.mricons.com/store/png/45804_11386_128_button_cancel_icon.png" height="35" width="35" onclick ="change()" />
<input type="text" name="name" value="name" id="ghd" />
JAVASCRIPT code
function change(){
var ab = document.getElementById('ghd').value;
document.getElementById('ghd').value = "";
$('#ghd').val('dsds');
}
Following is the link to jsfiddle also---
http://jsfiddle.net/nnRV5/
Hope it helps you!!
Try Following
<img src="view/image/delete.png" onclick="clearInput();">
<script>
function clearInput(){
document.getElementById('input_id').value = '';
}
</script>
Rather than using an anchor you could just listen for the click event on the image itself, like this:
<img id="clickable_image" src="delete.png" alt="Clear input text" />
<input id="the_input_to_clear" ... other attribs here ... />
<script>
(function(){
var image = document.getElementById('clickable_image'),
inputField = document.getElementById('the_input_to_clear'),
clickHandler = function() {
inputField.value = '';
};
if (image.addEventListener) {
// this attaches the event for most browsers
image.addEventListener("click", clickHandler, false);
} else {
// this attaches the event for IE...
image.attachEvent("onclick", clickHandler);
}
})();
</script>
From an accessibility perspective a clickable image that controls a form field is not good practice, but at least you're not having to worry about having an anchor that goes nowhere. If you want to improve the accessibility you might like to use a button element, and style it with a background image something like: http://jsfiddle.net/3vPpt/3/
The Javascript in my example dynamically attaches the click event to the image rather than specifying the function in the element's onclick attribute. This is to separate presentation from behaviour logic and is considered best practice.
The funky (function(){})(); notation executes the script immediately, but does not leak the variables created (image, inputField, clickHandler) into the global scope. This is also a best practice thing, and will prevent your script interfering with other code on the page.
Try this:
<script>
function clearField(input,val) {
if(document.getElementById(input).value == val){
document.getElementById(input).value = '';//This will clear the field
}
</script>
Related
I am working on a bootstrap environnement with classic asp.
I have a dynamically generated input fields
<input type="number" size="5" name="montantafacturer_<%=irs("INSPECTIONID")%>">
<button onclick="_EVENTSPARAM('events_ajouteralafacturation','<%=irs("INSPECTIONID")%>');">add</button>
There can be up to 100 dynamically generated fields on one page.
The basics are that i should fill the field montantafacturer_<%=irs("INSPECTIONID")%> with a numeric value and click on add to insert value in the database in a postback method
I am wondering if i can insert a javascript code to check if my field is filled rather than getting the field empty error from postback response... to gain time
ie :
<input type="number" size="5" name="montantafacturer_<%=irs("INSPECTIONID")%>">
<button onclick="**IF montantafacturer_<%=irs("INSPECTIONID")%>" IS NOT EMPTY THEN** _EVENTSPARAM('events_ajouteralafacturation','<%=irs("INSPECTIONID")%>');">add</button>
I wonder if this can be done via inline javascript.
Please advise how.
iid = irs("INSPECTIONID")
if iid <> "" then %>
<input type="number" size="5" name="montantafacturer_<%=iid%>">
<button onclick="_EVENTSPARAM('events_ajouteralafacturation','<%=iid%>');">add</button>
<$ end if %>
That way if your recordset is empty, no HTML is output. If you move the IF/THEN to just before the Button tag, then no button will be created for an empty value.
First of all, welcome to StackOverflow
Secondly ... It's been a very long while when I stopped using Classic ASP (more than 15 years ago), it's nice to see that he still has a small place out there :)
Last, but not the least... your question
as you have input and buttons, I'm sure you have a for loop and outside I will assume you have a <form> tag wrapping all inputs and buttons
To accomplish what you're trying to do, and making use of better code techniques, I would most likely end up with something as (and assuming that you can use jQuery to lift a bit of the javascript... let me know if you can't, and I'll re-write without it)
<form action="/yourpage.asp" method="POST">
<table class="table">
<tbody>
<% For ... %>
<tr class="tr-<%=irs("INSPECTIONID")%>">
<td>
<input
type="number"
size="5"
id="montantafacturer_<%=irs("INSPECTIONID")%>"
name="montantafacturer_<%=irs("INSPECTIONID")%>">
</td>
<td>
<button
class="btn"
data-event="events_ajouteralafacturation"
data-input="<%=irs("INSPECTIONID")%>"
>add</button>
</td>
</tr>
<% Next %>
</tbody>
</table>
</form>
<script>
$(function() {
// for every button with class "btn", fire "onButtonClick" fn upon click
$(".btn").on("click", onButtonClick);
});
function onButtonClick(evt) {
evt.preventDefault();
var btn = $(evt.currentTarget); // the clicked button
var btnEvent = btn.data("event");
var btnInput = btn.data("input");
// your logic
var input = $("#montantafacturer_" + btnInput).val();
if(input.length === 0) {
// show the error in any way you prefer
return;
}
// if we reach here, we have data in the input
_EVENTSPARAM(btnEvent, btnInput);
// you can now fire some code to submit the form
// or just this value, or even disable the button while it
// is being used to send the data (prevent double click), etc.
}
</script>
the <tr class="tr-<%=irs("INSPECTIONID")%>"> was a technique that I used back then so I could add a class that would mark that row with another color, to give some feedback to the user that something was happening with that row data, for example
$(".tr-" + btnInput).addClass("updating");
I've also added id to the input to use $("#...") instead of search by name
Small rant on using JS inline
Why would you ever use inline JS? It really isn't practical or readable - highly recommend moving that into an external source.
How to use JS inline (pls don't)
But if there is absolutely no way around for you, you can always just throw all your normal JS code inside an inline event like onclick.
<button onclick="
// this makes me sad
const allInputs = document.querySelectorAll('[name^=montantafacturer_]');
allInputs.forEach(input => {
if (input.value.length > 0 && !isNaN(input.value)) {
// number
} else {
// empty / Not a Number
}
});
">
add
</button>
This is about what you are looking for.
Mentions
Really, don't use inline JS
As pointed out by another user - you may want to use the HTML property required
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
I'm trying to create a form that allows user to edit the input through new window. PHP will process the input then append the new input with the new values. Apparently, when I try to edit the appended input, the JavaScript just won't fire. Please enlighten me on what I did wrong.
This is my html code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.races').click(function(e){
console.log("Inside Testing");
e.preventDefault();
var currID = this.id;
var content = '<form id="theForm" action="ct.php" method="post"> Race: <input type="text" id="race" name="race"><button type="submit" onClick="OKClicked()">Click this!</button></form>';
childWin = window.open('', "_blank", "height=400, width=550, status=yes, toolbar=no, menubar=no, location=no,addressbar=no");
toBeAdded = $(this).closest('div');
childWin.document.close();
childWin.document.write(content);
popupRace = childWin.document.getElementById("race");
parentRace = document.getElementById(currID);
transferValues();
})
});
function transferValues()
{
popupRace.value = parentRace.value;
}
function setValue(text)
{
childWin.close();
toBeAdded.parent().append(text);
toBeAdded.remove();
}
</script>
</head>
<body>
<div>
Name: <input type="text" name="name">
</div>
<div>
<div>
<input type="hidden" name="race-0" value="Human" id="race-0">
<span>race: Human</span>
Edit
</div>
</div>
<div>
Name: <input type="text" name="name">
</div>
<div>
<div>
<input type="hidden" name="race-1" value="God" id="race-1">
<span>race: God</span>
Edit
</div>
</div>
</body>
</html>
And this is my php code:
<?php
$postDataKey = array_keys($_POST);
$text = "";
foreach ( $postDataKey as $currPostKey )
{
$currValue = $_POST[$currPostKey];
$text .= '<div><input type="hidden" name="'.$currPostKey.'-1" value="'.$currValue.'" id="'.$currPostKey.'-1"><span>'.$currPostKey.': '.$currValue.'</span> Edit</div>';
}
echo
'
<html>
<head>
<script>
window.opener.setValue(\''.$text.'\');
</script>
</head>
</html>
'
;
?>
jQuery is only aware of the elements in the page at the time that it runs, so new elements added to the DOM are unrecognized by jQuery. To combat that use event delegation, bubbling events from newly added items up to a point in the DOM that was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go that high up the DOM tree. Ideally you should delegate to the nearest parent that exists at the time of page load.
You will likely want to change event handlers so they use the on() method.
This was solved in older versions of jQuery with the live function, opposed to the bindfunction.
The bind function attached an event to all the matching elements, as long as they existed in the moment of execution. Any element appended afterwards would be excluded.
The livefunciton would attach the event on any matching element, even if the element was created after the execution of the instruction.
On the present version of jQuery, bind and live has been replaced by on. The default behavior of on()is like bind. Fortunately there is a way to use on so that it works like live.
I wrote an article about it, which it may help you understand how.
To sum it up...
// This behaves like `bind`
$(".clickable").on("click", function(){...});
// This behaves like `live`
$(".parent-element").on("click", ".clickable", function(){...});
So just search the common parent element that all possible elements could possibly have (you could use $(document) if you do not want to think too hard) and you are golden.
jQuery on Method is what you're looking for; click the link and look for delegated events.
"Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. "
I'm trying to make some changes in DOM after an image is selected with an "input file" HTML5 element. So, I added a handler to the "onchange" event, but it is not working!
<span class="btn-file" >
Load and show alert
<input type="file" onchange="performSomeActions()"/>
</span>
And supose this is the function:
function performSomeActions(){
alert("lalala");
}
The error I get when I execute the code and after choosing a file is:
Uncaught ReferenceError: performSomeActions is not defined
I thought maybe I was wrong with the event name, but if you replace the input definition with the following line, it is working!
<input type="file" onchange="alert('alo');"/>
THE FIDDLE: http://jsfiddle.net/pvhaggrv/5/
Thanks in advance!
JSFiddle doesn't like calls to javascript embedded in your html. In the interest of keeping your code clean event handlers are assigned via javascript instead.
Change your html to:
<input type="file" id='fileInput'/>
and then in your JS
document.getElementById('fileInput').onchange = function() {
performSomeActions();
}
working fiddle: http://jsfiddle.net/bmartinelle/rhbphvhu/
just put javascript function in body tag just before ending of body tag like this
<span class="btn-file" >
Load and show alert
<input type="file" id="file" onchange="performSomeActions();"/>
</span>
<br/>
<img id="img"> </img>
<script>
var performSomeActions=function(){
alert("yyy");
}
</script>
see fiddle
Your fiddle doesn't work because fiddle executes all your javascript in the a anonymous function:
//<![CDATA[
window.onload=function(){
function performSomeActions(){
alert("yyy");
}
}//]]>
So your function isn't in the global scope and your HTML can't see it.
To your code works you need to include your function directly at the HEAD, you can do this in fiddle changing the checkbox at the left side: http://jsfiddle.net/pvhaggrv/12/
HOWEVER, you should not add event listeners this way, you should use addEventListener like kougiland said in his answer.
DEMO
HTML:
<span class="btn-file" >
Load and show alert
<input type="file" id="input">
</span>
<br/>
<img id="img"> </img>
SCRIPT:
function handleFiles() {
alert("lol");
var fileList = this.files; /* now you can work with the file list */
}
var inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
SOURCE:
Dynamically adding a change listener
I just want the user to click on a name and then it pops (alerts) some info. in the a tag if i don't pass any parameter it does alert something, it otherwise won't alert anything, even if i put something like this
<a href='javascript:sayThis('hi');'>
here's my html code (generated by some PHP):
PHP:
function showThis($color, $withFunctionYesOrNo, $first_levelIdFunction, $first_levelNameFunction, $first_levelLastNameFunction, $agent_email){
if($withFunctionYesOrNo == 'yes'){
$showThis = "<br>
<div>
<div style='margin-left:5%; border-left:6px solid ".$color."'>------
<a href='javascript:sayThis('".$agent_email."');'>
".$first_levelLastNameFunction.", ".$first_levelNameFunction." (ID: ".$first_levelIdFunction.")
</a>
<input type='submit' class='more' id='more' value='+' onclick='agentsBelow(".$first_levelIdFunction.")'>
</div>
<div style='margin-left:7%;' id=".$first_levelIdFunction."></div>
</div>";
}
return $showThis;
}
here is my JS code:
function sayThis(email){
alert(email);
}
First, I'd like to say that I would never use your coding practice. Not only do you have quote issues all over the place, but onclick the Event Object is passed to your Event Handler agentsBelow(). In these situations I do my code like this:
document.getElementById('more').onclick = function(e){
e = e || event; // don't even need to use the `e` argument above or this if not using the Event Object
agentsBelow('whatever');
}
Really, the style I'm showing is the way you should code, where your JavaScript is separate from your HTML. Of course, if you insist, you could just wrap your function within an Anonymous function in your HTML. Bad HTML practice:
onclick='function(){agentsBelow(\"you have String issues too\")}'
Note that you don't need to concatenate in double quotes. By the way:
onclick='agentsBelow(".$first_levelIdFunction.")'
using bad practice, should be:
onclick='function(){agentsBelow(\"$first_levelIdFunction\")}'
You are passing a variable to your JavaScript, not a String.
onclick='agentsBelow(".$first_levelIdFunction.")' could evaluate to:
onclick='agentsBelow(youFirstLevelIdFuntionVarResultIsNotaString)'
Still that wouldn't wouldn't work, since the Event Object would pass in.
Change this
<a href='javascript:sayThis('hi');'>
to this:
<a href='javascript:sayThis("hi");'>
change this
<a href='javascript:sayThis('".$agent_email."');'>
to
<a href='javascript:sayThis(\"".$agent_email."\");'>
I was making an HTML code editor, I tested all of the HTML tags I know and they all work, except for script tags.
When I type <script>something</script> into the text area and click a button, the script doesn't execute.
Please help! Here is the code:
<span id="finishedProduct">
<p>When you enter code, your finished product will be here! Don't worry, if you make a mistake you can fix it later!</p>
</span>
<form name="userCode">
<textarea name="userCode" cols="90" rows="20" placeholder="Type your code here"></textarea></br>
<button type="button">Run Code!</button>
</form>
<script>
function makeCode() {
var userCode=document.forms["userCode"]["userCode"].value;
document.getElementById('finishedProduct').innerHTML = userCode;
}
</script>
Here is the working code:
<span id="finishedProduct">When you enter code, your finished product will be here! Don't worry, if you make a mistake you can fix it later!
</span>
<form name="userCode">
<textarea name="userCode" cols="90" rows="20" placeholder="Type your code here"></textarea>
<br/>
<button type="button" onClick="makeCode()">Run Code!</button>
</form>
<script type="text/javascript">
function makeCode() {
var userCode=document.forms["userCode"]["userCode"].value;
document.getElementById('finishedProduct').innerHTML = userCode;
}
</script>
Here's a link to the JSFiddle: http://jsfiddle.net/Q2qLF/. I've removed some broken HTML, such as; a button shouldn't be contained in a anchor tag, I've added a 'onclick' in your button that will call the 'makeCode()' function and I've added the 'type="text/javascript"' into your script tag as this maximises compatibility.
Please let me know if you need any more help
I've updated my JSFiddle http://jsfiddle.net/Xanco/Q2qLF/1/
Now there are 2 textareas, one for the HTML and one for the Javascript. i've also created a new function called 'makejs', this takes the value of the Javascript textarea and runs it through a 'eval' - this executes the Javascript passed to it.
I've put the answer in a Fiddle here: http://jsfiddle.net/joshnicholson/P8eh9/
I'm not sure why you're wrapping the button element inside an anchor, but I would do it a slightly different way.
Here is the revised javascript:
var myButton = document.getElementById("btnRunCode");
myButton.addEventListener("click", makeCode);
function makeCode() {
var userCode=document.forms["userCode"]["userCode"].value;
document.getElementById('finishedProduct').innerHTML = userCode;
}
I added an id of "btnRunCode" to your button element, just to make things easier for me. See the Fiddle.