Hide/Show form in html? - javascript

I'm new to html and im trying to hide/show forms if the user ticks a box a form appears below it.
I have a form e.g.
Name :
Username :
Add More Users: (tickbox)
If the user ticks the 'Add More Users', another form with the fields 'Name,Username,Add More Users' appears below it. How is this possible?

HTML
<input type="checkbox" onclick="display(this)">Add more users</input>
<div id="yourDiv"> ...other forms... </div>
JavaScript
function display(e){
if (e.checked)
document.getElementById('yourDiv').style.display = 'block';
else
document.getElementById('yourDiv').style.display = 'none';
}
An even better way to do this (thanks to What)
HTML
<input id="more" type="checkbox">Add More Users</input>
<div id="yourDiv"> ...other form... </div>
JavaScript
window.onload = function () {
document.getElementById('more').onclick = function () {
if (this.checked)
document.getElementById('yourDiv').style.display = 'block';
else
document.getElementById('yourDiv').style.display = 'none';
}
}

You will need to use scripts for that.
First of all put the form you want to Show/Hide inside a <div id="myForm"> tag
and enclose it with
Then use jQuery http://www.jquery.com (download the jquery library and link it to your page and add an event at the loading of the page to run a function to check if the combo box is checked then execute:
("#myForm").toggle();

You can use .clone() and .append() (requires jQuery). You have give name attribute like
<input type="text" name="test[]" />

Related

How do I make html run a javascript function when a user clicks a button?

I have a web form where users will type in a name of a person then click a button to open a page about that person. e.g. They type Player One and it runs a function which opens the file C:\PlayerOne.
I've tried using the <button> tag and adding the onclick element to run the function, but I was unable to diagnose the problem there either. The Event Listener stuff I am not too familiar with, but I saw it [here] (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/button) so I thought I'd try it that way instead.
<form>
<fieldset>
<legend>Enter player name: </legend>
First name:<br>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname"><br><br>
<input type="button" value="Submit">
</fieldset>
<script>
const input = document.querySelector('button');
input.addEventListener('click', UseData);
function UseData()
{
var Fname=document.GetElementById('firstname');
var Lname=document.GetElementById('lastname');
window.location = "C:\" + Fname + Lname;
}
</script>
</form>
I want the user to be able to type the name and open the appropriate file, as explained above. However, the button at this point simply does nothing. I do have a test file for it to reference, which I have been typing the name of in the fields of the form.
It's because there's no button tags in your form. Use the attribute selector like so instead:
const input = document.querySelector('input[type="button"]');
Here is an example of similar code by me involving a button triggering a function
The button:
<button onclick="theFunction()">sampletext</button>
The script:
var x = document.getElementById("sampleElement");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
In my example, the button is used to show/hide a div. Clicking my button triggers the function which changes the div visibility.

jquery/javascript convert a plain text message into a text input field

i've got the following request:
create a plain text field that transforms into an text input element when clicking on an edit trigger. When leaving the input element the text will be stored in the database and the field is transformed back into a plain text field with the new content. When ESC is pressed in the input the recent value is restored. To do this i use the following code:
<div id="value"><span id="text">some text</span></div>
<div id="trigger">[EDIT]</div>
<div style="display: none;" id="storage">
<input type="text" id="input" value="some text"/>
</div>
<script type="text/javascript">
$('#trigger').click(function() {
var t = $('#text').detach();
var e = $('#input').detach();
$('#storage').append(t);
$('#value').append(e);
e.focus();
});
$('#input').blur(function() {
var t = $('#text').detach();
var e = $('#input').detach();
if (t.text() != e.val()) {
$.getJSON(...);
}
$('#storage').append(e);
$('#value').append(t);
});
$('#input').keyup(function(event) {
if (event.which == 27) {
$('#input').val($('#text').text());
$('#input')[0].blur();
}
});
</script>
Thanks to #nnnnnn this now works. But is there maybe a simpler way to implement this using some preexisting API functions?
thanks very much.
use jquery editable here is a link
for demo:
http://www.appelsiini.net/projects/jeditable/default.html
for plugin home page
http://www.appelsiini.net/projects/jeditable
I developed a plugin that do what you need:
$.convertTo
I hope it will be helpful, regards.

Best way to pass JS/ css info to a form

I am sure this is so easy and I'm just a huge huge noob. I have a form on a PHP page, and it has a few normal form elements (1 textarea, 1 text field).
I am also dynamically adding 100 small images to the page, which are random, and I am using JQuery to let someone select or deselect these images:
Here is the html that loops 100 times to display the images:
<div class='avatar'><img class='avatar_image' src='$this_profile_image' name='$thisfriend'></div>
and here is the Jquery:
<script type="text/javascript">
$(document).ready(function() {
$(".avatar_image").click(function() {
$(this).toggleClass("red");
});
});
</script>
What I want to do is, when the form is submitted, have the script that processes it be able to tell which of those 100 images is selected (so it's class will be "red" instead of "avatar_image"). I am blanking on this.
You'll need to add hidden inputs with some kind of identifiers for those images, and toggle the state of those inputs based on the image selected-ness. Something like this:
Change your image markup:
<div class='avatar'>
<img class='avatar_image' src='$this_profile_image' name='$thisfriend'>
<input type="hidden" name="avatar_image[]" value="$this_profile_image" disabled="disabled" />
</div>
Change jQuery binding (and use event delegation, maybe pick a better container than document.body):
<script type="text/javascript">
$(function() {
var selClass = 'red';
$(document.body).on('click', ".avatar_image", function() {
var $this = $(this);
var $inp = $this.siblings('input[type="hidden"]');
var isSelected = $this.hasClass(selClass), willBeSelected = !isSelected;
$this.toggleClass(selClass);
if(willBeSelected) {
$inp.removeAttr('disabled');
} else {
$inp.attr('disabled', 'disabled');
}
});
});
</script>
Read the submitted data in PHP (assuming you're submitting via a POST form):
$selectedImages = $_POST['avatar_image'];
Add a ID to each image, when its clicked grab the id and then inject it into a hidden textfield
<input type="hidden" name="avatar" id="avatar" value="" />
$(".avatar_image").click(function() {
$(this).toggleClass("red");
//assign its id to the hidden field value
$("input[name='avatar']").attr('value', $(this).attr('id'));
// pass that to your DB
});
I presume your using ajax to grab this data back
success : function(callback){
$("image[id*='"+callback.avatar+"']").addClass('red');
}
Try this
PHP: Add the id for the friend to the html you had
<div class='avatar'>
<img class='avatar_image' src='$this_profile_image' name='$thisfriend' data-id='$thisFriendsId>
</div>
JS: Create an empty array. Use each function to go through push the selected id into your array. Then use post to submit to your php.
selected = [];
$(function(){
$(".avatar_image").click(function() {
$(this).toggleClass("red");
});
$('.submit').click(function(){
$('.red').each(function(){
var selectedId = $(this).data('id');
selected.push(selectedId);
});
$.post ('http://mysite.com/process.php', selected, function() { alert('succes!'); });
});
​});​

Change/Get check state of CheckBox

I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I've tried something like this but it won't work.
JavaScript function
function checkAddress()
{
if (checkAddress.checked == true)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onchange="checkAddress()" />
Using onclick instead will work. In theory it may not catch changes made via the keyboard but all browsers do seem to fire the event anyway when checking via keyboard.
You also need to pass the checkbox into the function:
function checkAddress(checkbox)
{
if (checkbox.checked)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onclick="checkAddress(this)" />
You need to retrieve the checkbox before using it.
Give the checkbox an id attribute to retrieve it with document.getElementById(..) and then check its current state.
For example:
function checkAddress()
{
var chkBox = document.getElementById('checkAddress');
if (chkBox.checked)
{
// ..
}
}
And your HTML would then look like this:
<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()"/>
(Also changed the onchange to onclick. Doesn't work quite well in IE :).
I know this is a very late reply, but this code is a tad more flexible and should help latecomers like myself.
function copycheck(from,to) {
//retrives variables "from" (original checkbox/element) and "to" (target checkbox) you declare when you call the function on the HTML.
if(document.getElementById(from).checked==true)
//checks status of "from" element. change to whatever validation you prefer.
{
document.getElementById(to).checked=true;
//if validation returns true, checks target checkbox
}
else
{
document.getElementById(to).checked=false;
//if validation returns true, unchecks target checkbox
}
}
HTML being something like
<input type="radio" name="bob" onclick="copycheck('from','to');" />
where "from" and "to" are the respective ids of the elements "from" wich you wish to copy "to".
As is, it would work between checkboxes but you can enter any ID you wish and any condition you desire as long as "to" (being the checkbox to be manipulated) is correctly defined when sending the variables from the html event call.
Notice, as SpYk3HH said, target you want to use is an array by default. Using the "display element information" tool from the web developer toolbar will help you find the full id of the respective checkboxes.
Hope this helps.
You need this:
window.onload = function(){
var elCheckBox=document.getElementById("cbxTodos");
elCheckBox.onchange =function (){
alert("como ves");
}
};
Needs to be:
if (document.forms[0].elements["checkAddress"].checked == true)
Assuming you have one form, otherwise use the form name.
As a side note, don't call the element and the function in the same name it can cause weird conflicts.
<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />
I know this is late info, but in jQuery, using .checked is possible and easy!
If your element is something like:
<td>
<input type="radio" name="bob" />
</td>
You can easily get/set checked state as such:
$("td").each(function()
{
$(this).click(function()
{
var thisInput = $(this).find("input[type=radio]");
var checked = thisInput.is(":checked");
thisInput[0].checked = (checked) ? false : true;
}
});
The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object!
ENJOY!
This is an example of how I use this kind of thing:
HTML :
<input type="checkbox" id="ThisIsTheId" value="X" onchange="ThisIsTheFunction(this.id,this.checked)">
JAVASCRIPT :
function ThisIsTheFunction(temp,temp2) {
if(temp2 == true) {
document.getElementById(temp).style.visibility = "visible";
} else {
document.getElementById(temp).style.visibility = "hidden";
}
}
var val = $("#checkboxId").is(":checked");
Here is a quick implementation with samples:
Checkbox to check all items:
<input id="btnSelectAll" type="checkbox">
Single item (for table row):
<input class="single-item" name="item[]" type="checkbox">
Js code for jQuery:
$(document).on('click', '#btnSelectAll', function(state) {
if ($('#btnSelectAll').is(':checked')) {
$('.single-item').prop('checked', true);
$('.batch-erase').addClass('d-block');
} else {
$('.single-item').prop('checked', false);
$('.batch-erase').removeClass('d-block');
}
});
Batch delete item:
<div class="batch-erase d-none">
<a href="/path/to/delete" class="btn btn-danger btn-sm">
<i class="fe-trash"></i> Delete All
</a>
</div>
This will be useful
$("input[type=checkbox]").change((e)=>{
console.log(e.target.checked);
});

Targeting a button on a form to press, with javascript

I know that, using Javascript, I can tell a form to submit using something like this:
document.forms[0].submit()
However, if there are a number of forms on a page, which could be in any order, how would I target the submit link in this form:
<form action="/services/auth/" method="post">
<div id="auth-allow-container" class="button-container">
<a class="Butt" id="auth-allow" type="submit" href="#"><span>SUBMIT</span></a>
<a class="Butt CancelButt" id="auth-disallow" href="#home"><span>CANCEL</span></a>
</div>
</form>
..so that it is as if the user has clicked SUBMIT?
You could make a function:
function submitFormById(id) {
var el = document.getElementById(id);
while ( el && el.tagName.toLowerCase() != 'form') {
el = el.parentNode;
}
el && el.submit();
}
Then you use this function like so:
submitFormById('auth-allow');
submitFormById('auth-disallow');
Both will submit the form.
Give the form a name attribute. Then you can do document.name.submit(). i.e.
<form name="MyForm" ....>
<input ... />
</form>
You would then be able to do document.MyForm.submit()
EDIT:
As you have said you can't change the html, solutions adding an ID are also no help. You will have to identify which numerical form element on the page this specific one is and do docuemnt.forms[x].submit() where x is the index of this form.
put in the link:
onclick="this.parentNode.parentNode.submit();"
this is a bit fragile if you change the dom structure but it is a generic link for this kind of form
update:
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("auth-allow").addEventListener("click", submithAuthForm, false);
}, false);
function submithAuthForm(){
document.getElementById('auth-allow').parentNode.parentNode.submit();
}

Categories

Resources