How to use the ons-switch

Asked 1 years ago, Updated 1 years ago, 60 views

I am studying programming at Monaca Cloud IDE.

I tried to change the contents of the P tag using the ons-switch method isChecked by referring to the monaca official guidebook HTML5 hybrid app development, but it didn't work. (The ons-switch is shown, but the contents of the P tag have not been changed.)
I look forward to your kind cooperation.

<!DOCTYPE HTML>
<html>
 <head>
  <metacharset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scale=no">
  <meta http-equiv="Content-Security-Policy" content="default-src*data:;style-src*'unsafe-inline';script-src*'unsafe-inline'"unsafe-eval'">
  <script src="components/loader.js"></script>
  <link rel="stylesheet" href="components/loader.css">
  <link rel="stylesheet" href="css/style.css">
  <script>
    ons.bootstrap();
  </script>
 </head>
 <body>
    <ons-switch var="myswitch" checked onclick="switchClicked()">/ons-switch>
    <pid="info"><p/>
   <script>
      function switchClicked(){
      document.querySelector('#info').text(mySwitch.isChecked());}
   </script>  
  </body>
 </html>

javascript monaca onsen-ui

2022-09-30 16:33

3 Answers

When using the Monaca debugger, the following error is displayed:

Uncaught ReferenceError: mySwitch is not defined

var="myswitch" coding error.

If you correct it and check it again, the following error will be displayed.

Uncaught TypeError: Object# has no method 'text'

What is written in the book is not always correct.

 document.querySelector('#info').innerHTML=String(mySwitch.isChecked());

or

 document.querySelector('#info').textContent=String(mySwitch.isChecked());

works by doing .

See also HTML DOM querySelector()Method.


2022-09-30 16:33

How about this?

<script>
    function switchClicked(){
        $('#info').text(mySwitch.isChecked());
    }    
</script>


2022-09-30 16:33

IsChecked() only returns true when the switch is on, so I don't think it's the expected movement.
https://ja.onsen.io/v1/reference/ons-switch.html#methods-summary

function switchClicked(){
  if(myswitch.isChecked()==true){
  document.querySelector('#info').text('On');
  } else{
  document.querySelector('#info').text('Off');
  }
}


2022-09-30 16:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.