I want to add three buttons on a web form. Each button has its own id. When I click a button, I want the content of a div to become visible and others to be hidden. However, now I use three functions that add as an event to each button. Is there a smart way to create one function and add the elementId as a parameter? I want to "trap" the requesting object.
function myCoolFunction(parameter) {
if(parameter=="button1") {
hilight("button1");
}
if(parameter=="button2") {
// do something else for example
}
}
Thanks,
Try this:
<input type="button" value="Click Me" id="button1" onClick="myCoolFunction(this.id);" />
If you're interested in jquery...
html
<div id="box_1"></div>
<div id="box_2"></div>
<input type="button" data-id="box_1" />
<input type="button" data-id="box_2" />
js
$("input:button").click(function(e) {
var id = $(this).attr("data-id"),
boxes = $(".boxes"),
boxes.hide().filter("#"+id).show();
e.preventDefault();
})
Using custom data attributes
Markup
<input type="button" value="button one" onClick="myCoolFunction(this)" data-related-div="div_one" />
<div id="div_one" />
<input type="button" value="button two" onClick="myCoolFunction(this)" data-related-two="div_one"/>
<div id="div_two" />
<input type="button" value="button three" onClick="myCoolFunction(this)" data-related-div="div_three" />
<div id="div_three" />
Script
function myCoolFunction(button) {
highlight(button.dataset.relatedDiv);
}
Note that if you add a new button you don't have to modify the javascript code.
Also, this might break in crappy browsers (e.g. IE).
Update (for those who didn't follow the original link):
The dataset attribute is (at the moment) Webkit only. Custom attributes can be accessed using getAttribute and setAttribute in all modern browsers though.
Related
I'm tryin to set a function inside a for loop within a c# cshtml file. The purpose of this function is to unhide photos on button click so users can see them.
#if (Model.Photos.PhotosBase64 != null)
{
for (var i = 0; i < Model.Photos.PhotosBase64.Count; i++)
{
<h1 class="font-weight-bold">Photo #(i + 1)</h1>
<input type="button" value="Show Button" onclick="showImage();"/>
<img alt="" id="loadingImage_#i" src="data:image/png;base64, #Model.Photos.PhotosBase64.ElementAt(i)" style="visibility:hidden"/>
<br/>
<br/>
#Html.HiddenFor(modelItem => Model.Photos.PhotosBase64[i])
<input type="submit" value="Remove Photo" class="btn btn-danger" id="removephoto-btn" asp-action="RemovePhoto" asp-route-index="#i" />
<br/>
<br/>
<%= function showImage(){document.getElementById('loadingImage_'+i).style.visibility="visible";}> </%>
}
}
I've read that <%=> can open up a javascript section but it doesn't seem to be working correctly probably because of my missing syntax or using it in the wrong context. I've tried several different formats but left the most recent attempt on the page for some visualization. How can I use JS to hide/unhide photos by selecting their ID? (or other method if more effective)
For starters, JavaScript code goes in a <script> element.
Aside from that, the logic of what you're doing is a bit odd. Consider that you are outputting this code in a loop. Which means the page is going to have many different versions of a function called showImage, each one over-writing the previous. So only the last one will actually be called.
Define one function (probably at the bottom of the page, certainly not in a loop) which performs the operation you want, and have it require whatever information it needs to perform that operation. In this case that information is the id of the target element:
<script type="text/javascript">
function showImage(id) {
document.getElementById(id).style.visibility="visible";
}
</script>
Then within the loop you can invoke that function, supplying the id values accordingly:
<input type="button" value="Show Button" onclick="showImage('loadingImage_#i');"/>
This the answert
#if (Model.Photos.PhotosBase64 != null)
{
for (var i = 0; i < Model.Photos.PhotosBase64.Count; i++)
{
<h1 class="font-weight-bold">Photo #(i + 1)</h1>
<input type="button" value="Show Button"
onclick="showImage('loadingImage_#i');"/>
<img alt="" id="loadingImage_#i" src="data:image/png;base64,
#Model.Photos.PhotosBase64.ElementAt(i)" style="visibility:hidden"/>
<br/>
<br/>
#Html.HiddenFor(modelItem => Model.Photos.PhotosBase64[i])
<input type="submit" value="Remove Photo" class="btn btn-danger" id="removephoto-btn" asp-action="RemovePhoto" asp-route-index="#i" />
<br/>
<br/>
}
}
<script type="text/javascript">
function showImage(id) {
document.getElementById(id).style.visibility="visible";
}
</script>
You have to have a javascript method to make photos visible. and yo must pass yor desired image id to that function
I am using jaquery and jquery mobile version 1.8 and I have a button like so:
<div class="ui-bar-a" id="myButton" style="bottom:0;position: fixed;width: 100%">
<input type="submit" name="Next" id="NextButton" value="Save" />
</div>
And I have a javascript that can change the text for it like so:
$('#AnyButton').live('click', function() {
if(true)
{
$('#myButton div').text('Saving')
}
else
$('#myButton div').text('Continue');
});
I tried so many other ways that didn't work but this works however after I change the text the button seems to replace the myButton div content with the text Saving or Continue and thus the button is no longer clickable.
In my browser debugger the button shows a text Save appear between myButton and the Nextbutton input.
Like so:
<div class="ui-bar-a" id="myButton" style="bottom:0;position: fixed;width: 100%">
"Save"
<input type="submit" name="Next" id="NextButton" value="Save" />
</div>
I suspect there is more to your code than you have presented. With jQuery Mobile, each input is read as a Button. So you mnay need to refresh it after a dynamic update.
This code is working:
$(function() {
$("#NextButton").click(function(e) {
e.preventDefault();
$(this).val("Saving").button("refresh");
});
});
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<div class="ui-bar-a" id="myButton" style="bottom:0;position: fixed;width: 100%">
<input type="submit" name="Next" id="NextButton" value="Save" />
</div>
See More: https://api.jquerymobile.com/button/ and https://demos.jquerymobile.com/1.4.5/button/
If I am reading your post correctly, you want to change the text of the
input, you need to change it's value property.
I think .live is relatively old and deprecated and should be replaced with .on and a delegated event handler
$('#AnyButton').live('click', function() {
if(true)
$('#myButton').find('input[type="submit"]').val('Saving');
else
$('#myButton').find('input[type="submit"]').val('Continue');
});
In my Web Application
I need to Apply common java script method for all Button when onclick action occur
For example
For all following buttons need to apply onclick="commonOnClickJavaScript();"
<h:commandButton id="createCarButton"
title="Create Car"
action="#{carController.add}" styleClass="submit_btn" />
<h:commandButton id="editCarButton"
title="Edit Car"
action="#{carController.edit}" styleClass="submit_btn" />
<h:commandButton id="createDoorButton"
title="Create Door"
action="#{doorController.add}" styleClass="submit_btn" />
<h:commandButton id="editDoorButton"
title="Edit Door"
action="#{doorController.edit}" styleClass="submit_btn" />
The native solution is taht
To embed onclick="commonOnClickJavaScript();" in every button
For example
<h:commandButton id="createCarButton"
title="Create Car"
action="#{carController.add}" styleClass="submit_btn"
onclick="commonOnClickJavaScript();" >
But in my application
I need to apply that for hundreds of buttons
so this solution will not be simple and waste a lot of time
Any Ideas?
How about something like this fiddle, have a selector retrieving all the buttons and a small JavaScript to apply the event listener to all your buttons?
Hope this is what you were looking for.
<input id="Button1" type="button" class="myButton" value="Button1">
<input id="Button2" type="button" class="myButton" value="Button2">
<input id="Button3" type="button" class="myButton" value="Button3">
var handleButtonClick = function () {
alert('Button clicked');
},
buttonArray = $('.myButton');
$.each(buttonArray, function (index, item) {
item.addEventListener('click', function() {
handleButtonClick();
}, false);
});
I have a complicated case here, but below is an example just to make it simple.
I have two buttons, each with their own onClick function. I want to call the onClick function of button A when I click on button B.
<input id="buttonA" type="button" value="BUTTON A" onMouseUp="sayHiA()"></input>
<input id="buttonB" type="button" value="BUTTON B" onClick="sayHiB()"></input>
Note that the event can be onClick() or onMouseUp()
p.s. I have to do it using only javascript. (NO jQuery). Thanks
<input type="button" onclick="fnc()"/>
<input type="button" id="message" onclick="alert('ok')" />
<script type="text/javascript">
function fnc()
{
document.getElementById("message").click();
}
</script>
are you looking for this?
<html>
<head>//I guess something like setTimeout(function,timeInMilliseconds)
<script language = "javascript">
function sayHiA(){
var v = document.getElementById('buttonB').getAttribute("onClick");
setTimeout(v,0);
}
function sayHiB(){
document.getElementById('para').innerHTML = 'wrote';
}
</script>
</head>
<body>
<input id="buttonA" type="button" value="BUTTON A" onMouseUp="sayHiA()"></input>
<input id="buttonB" type="button" value="BUTTON B" onClick="sayHiB()"></input>
<p id = "para">
Write Here
</p>
</body>
</html>
function sayHiB() {
sayHiA();
}
Did you tried this with an external js ? This is quite the most basic thing you can do in javascript.
I made you a jsfiddle : http://jsfiddle.net/pjDVP/4/
The html :
<input id='bta' type='button' value='button a'></input>
<input id='btb' type='button' value='button b'></input>
The js (with jquery laoded) :
$(function(){
$('#bta').click(function(){aORbClick();});
$('#btb').click(function(){aORbClick();});
})
function aORbClick(){alert('I clicked a or b');}
just call function sayHiA from sayHiB or call it after.
Call from sayHiB
function sayHiB()
{
sayHiA();
}
or after
<input id="buttonB" type="button" value="BUTTON B" onClick="sayHiB(); sayHiA();"></input>
or easier way is to use jQuery, so you can do this
function sayHiB(){
if($('#id-of-a').attr('onclick'))
$('#id-of-a').click();
else if ($('#id-of-a').attr('onmouseup'))
$('#id-of-a').mouseUp();
}
function sayHiB(){
$('#buttonA').click();
}
Raw JS:
function sayHiB(){
var buttonA = document.getElementById('buttonA');
buttonA.onclick.apply(buttonA); // in onclick function you can get buttonA as 'this'
}
I'd probably make a generic function that switches on the button's name/id to figure out what to do - this would also make your code work independent of the event attribute used to call the function.
HTML:
<input id="buttonA" type="button" value="BUTTON A" onMouseUp="myFunc(this)"></input>
<input id="buttonB" type="button" value="BUTTON B" onClick="myFunc(this)"></input>
JavaScript:
function myFunc(elem){
switch(elem.id){
case 'buttonA':
sayHiA();
break;
case 'buttonB':
sayHiB();
sayHiA();
break;
}
}
This would also help with any DOM manipulation you might need as the button which was clicked is passed to the generic function myFunc, allowing you to quickly access other attributes or nearby elements.
I'm working with MVC 3, javascript and jQuery.
I've got a hidden button which click() function needs to be called from javascript.
This works great on every browser except IE9.
$('#fakeSubmitBt').click(function () {
$('#fileUplSubmitBt').click();
});
Here, fileUplSubmitBt is the hidden button and fakeSubmitBt is the visible button which I need to click instead.
I noticed that if a call three times
$('#fileUplSubmitBt').click();
then the form is submitted, but in the backend the elements of the form are not recognized.
UPDATE:
thanks to the hints given by Ricardo and Jay, I tried to use trigger('click') but also this path failed.
In the following I post the code that is shaming me (it's MVC3 using Razor):
<script type="text/javascript">
function s2cPanelReady() {
$('#fakeBrowseBt').click(function () {
$('#fileUplRadio').prop("checked", true);
$('#gravatarRadio').prop('checked', false);
$('#realFileUpload').click();
});
$('#fakeSubmitBt').click(function () {
if ($('#gravatarRadio').prop("checked")) {
$('#grvatarSubmitBt').click();
} else if ($('#fileUplRadio').prop("checked")) {
$('#fileUplSubmitBt').trigger('click');
}
});
}
</script>
<div class="inputForm">
<div class="inputField">
<div class="userPicLargeFrame">
<img src="/Images/Get?id=#Model.ID&size=40" class="userPicLarge" />
</div>
</div>
#using (Html.BeginForm("ChangePicture", "User"))
{
<div class="inputField">
<input type="radio" id="gravatarRadio" />
<span class="inputLabel">Gravatar:</span>
#Html.EditorFor(model => model.Preferences.GravatarEmail)
#Html.ValidationMessageFor(model => model.Preferences.GravatarEmail)
</div>
<input id="grvatarSubmitBt" type="submit" value="Save Pic" style="display:none;" />
}
#using (Html.BeginForm("UploadPicture", "User", FormMethod.Post, new { encType = "multipart/form-data", name = "uplPicForm" }))
{
<div class="inputField">
<input type="radio" id="fileUplRadio" />
<span class="inputLabel">Save your own pic:</span>
<span class="inputLabel">
<span style="display:inline-block; position:relative;">
<input type="file" id="realFileUpload" name="fileUpload" style="position:relative; opacity:0; -moz-opacity:0 ;" />
<span style="display:inline-block; position:absolute; top:0px; left:0px;">
<input id="fakePathBox" type="text" value="" readonly />
<input id="fakeBrowseBt" type="button" value="..."/>
</span>
</span>
</span>
<input id="fileUplSubmitBt" type="submit" name="submit" value="Upload" style="display:none;" />
</div>
}
<div class="inputField">
<span class="inputLabel">
<input id="fakeSubmitBt" type="button" value="Submit" class="s2cButton" />
</span>
</div>
</div>
UPDATE N.2: I tried to remove all javascript stuff, and simply put the file upload HTML tag with a simple submit button: nor in this case on IE9 I'm able to submit the form!!
Sometimes it runs, sometimes it is not fired at the first click, but only at the second click (and in this case the submitted form hasn't got the selected file, so server-side this results in an error...), sometimes it simply doesn't fire the submit button, no matters how many click I do.
This issue starts to make me crazy....
Any other hint?
Thank you very much!
Best
cghersi
I've had a similar problem and ended up just transforming the button into an anchor (<a>) and invoked the jquery-ui function $.button()
NOTE: the jquery ui is required http://jqueryui.com/
That way the link still looked like a button and the $.click() event worked.
html
<div class="input">
Submit
</div>
jquery
$("#emulate-button").button();
//Set event when clicked
$("#emulate-button").click(function () {
//.... your logic here
});
Like Ricardo said, you need to use trigger: http://jsfiddle.net/5hgsW/1/
If the $('#fileUplSubmitBt').click event wasn't defined in JQuery, the .click() trigger may not work.
Put everything from the $('#fileUplSubmitBt').click event inside a function then bind it in the $('#fakeSubmitBt').click and $('#fileUplSubmitBt').click events.