Change Image Url on Button Click using JavasSript in ASP.Net

sarash
 
on Apr 27, 2021 02:37 AM
449 Views

hello everyone

I use C# Asp.net and I want to use javascript codes on it 

I define image on the page and 2 buttons now I want to when users click on buttons it will change image URL so I wrote the below codes:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="bulb.aspx.cs" Inherits="bulb" %>

<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>UserCode | Js | 49</title>
    <script>
        var $ = document;
        var bulbPic = $.getElementById("bulbPic")

        function turnOnTheBulb() {
            bulbPic.src = "pics/bulbon.gif"
        }

        function turnOffTheBulb() {
            bulbPic.src = "pics/bulboff.gif"
        }


    </script>

    <style>
        #container {
            margin-top: 100px;
            margin-left: 600px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div id="container">
            <br />
            <asp:Image ID="bulbPic" runat="server" ImageUrl="~/pics/bulboff.gif" />
            <br />
            <br />
            <br />
            <asp:Button ID="turnOn" runat="server" Text="on" OnClientClick="return turnOnTheBulb()" />
            <asp:Button ID="turnOff" runat="server" Text="off" OnClientClick="return turnOffTheBulb()" />
        </div>
    </form>
</body>
</html>

but it doesn't work for me

can anyone help me?

Thanks 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Apr 27, 2021 02:41 AM

Hi sarash,

Refer below code.

HTML

<div id="container">
    <asp:Image ID="bulbPic" runat="server" ImageUrl="~/pics/bulboff.gif" />
    <br />
    <br />
    <br />
    <asp:Button ID="turnOn" runat="server" Text="on" OnClientClick="return turnOnTheBulb()" />
    <asp:Button ID="turnOff" runat="server" Text="off" OnClientClick="return turnOffTheBulb()" />
</div>
<script>
    var $ = document;
    var bulbPic = $.getElementById("bulbPic");
    function turnOnTheBulb() {
        bulbPic.src = "pics/bulbon.gif";
        return false;
    }

    function turnOffTheBulb() {
        bulbPic.src = "pics/bulboff.gif"
        return false;
    }
</script>
<style>
    #container {
        margin-top: 100px;
        margin-left: 600px;
    }
</style>

Screenshot