jhunlio
jhunlio

Reputation: 2660

simple javascript convert into function

I have a simple javascript that i keep using in every page I have, and I want to make it a function and add some additional feature, if i click that loading_input(div) from display:block change to display:none

I try but I have no luck can someone guide me to make it work..

example:

<script type="text/javascript">
 document.getElementById("instructor").onchange = function() {
    document.getElementById("loading_input").style.display = "block";
    document.getElementById("instructor").style.color = "#fff";
}
document.getElementById("subject_scheduling").onchange = function() {
    document.getElementById("loading_input").style.display = "block";
    document.getElementById("subject_scheduling").style.color = "#fff";
}

</script>

Upvotes: 0

Views: 52

Answers (3)

jhunlio
jhunlio

Reputation: 2660

Thank you for all suggestion it help me to come up with this answer.

// To haddle my onchange this is what I come up 
function loading(input_id){
  if(input_id){
    document.getElementById("loading_input").style.display = "block";
    document.getElementById(input_id).style.color = "#fff";
  }
 }

If I need to use it in my page. I just do like this

<input id="sample" onchange="loading('sample')" />

onclick event

 // this is what I come up to haddle my onclick event 
 function close_and_reload(id){
 if(id){
    document.getElementById(id).style.display = "block";
    window.location.reload();
 }
}

Upvotes: 1

SK.
SK.

Reputation: 4358

Try this.

<!DOCTYPE html>
<html>
<body>

<p>Select a new car from the list.</p>

<select id="mySelect" onchange="changeStyle('demo');changeColor('demo')">
  <option value="Audi">Audi
  <option value="BMW">BMW
  <option value="Mercedes">Mercedes
  <option value="Volvo">Volvo
</select>


<p id="demo">some content</p>

<script>
function changeStyle(id) {
    document.getElementById(id).style.display = "block";
}

function changeColor(id) {
   document.getElementById(id).style.color = "#fff";
}
</script>

</body>
</html>

Upvotes: 0

Alp
Alp

Reputation: 3105

I made both element Ids parameters to the function, although the code snippet you sent seems like you only change the 2nd one. My version is a bit more flexible but if you know for sure the first one always the same, then you can drop the first parameter.

function changeHandler(elem1, elem2){
    document.getElementById(elem1).style.display = "block";
    document.getElementById(elem2).style.color = "#fff";

} 


document.getElementById("instructor").onchange = changeHandler("loading_input", "instructor");

document.getElementById("subject_scheduling").onchange = changeHandler("loading_input", "subject_scheduling");

Upvotes: 0

Related Questions