Checkbox and radio

hello every body

how to get the data in the HTML fields by ruby, I did a form test that contains a checkbox or a radio, but I noticed that add.call_back does not get the data checkbox or radio, however I did the test separately to see the result, I also noticed that it works well with an input type text or type range

thank you

I moved you to the Ruby category, which you should use for this type of query…

it’s also best to add a properly formatted ‘failing’ snippet when asking for help…

:add-action_callback does work for radio and checkbox, with both webDialogs and HtmlDialogs but you don’t state which you are testing…

the more explicate your question, the quicker the response’s…

john

1 Like
dlg_html ='<html>   
<head>      
<script type="text/javascript">         
function sendPoints()        
{ 
var ids = new Array ("x1", "x2","x3")          
var arg = "" ; var entry = "" ; var valid = true ;            
// Iterate through the text boxes to form output argument   

for (i in ids)           
{              
             entry = document.getElementById(ids[i]).value               
               if ((entry.length == 0) || isNaN(entry))               
                  {                  
                    valid = false ;              
                     }             
               else              
              {                 
                arg = arg + entry + ",";             
               }           
                      }          
// Send argument to SketchUp script for processing            
                    if (!valid)            
                    {               
                    arg = "" ;             
                      }            
          window.location = \'skp:dlg_html@\' + arg ;           
}           
</script>   
</head>
 <body>     
 <!-- Location of the first vertex -->      
 Point 1:      
 <input type="text" id="x1" value="0.0" size="10" maxlength="6"/>      
     
 <input type="checkbox" id="x2" value="true" size="10" maxlength="6"/>     
      
 <input type="radio" id="x3" value="false" size="10" maxlength="6"/>      
          
     
    
 <br /><br />      
 <!-- Send points to JavaScript -->     
 <input type="submit" onclick="sendPoints();"value="Create Point" />   
 </body> 
 </html>' 
 
point_dialog= UI::WebDialog.new("dlg_html")


point_dialog.set_html(dlg_html)

point_dialog.add_action_callback("dlg_html") {|dialog, arg| 
arr= arg.to_s

UI.messagebox(arr)
 

  
}
# Display the dialog box
if RUBY_PLATFORM.index  "drawin"  
 point_dialog.show_modal 
else  
 point_dialog.show 
end

I created a messagebox to display the values ​​to recover, but by testing, the messagebox does not display anything but the code works, yet when I put numeric values ​​the messagebox displays an array with one of the values ​​entered

Messageboxes can fail silently if the string argument is not a valid string. So do not use them for debugging.

Open the console and send strings to STDOUT using the global puts() method.

THank you Dan
i will try again and will return

the errors lay in your javascript…

if you try a HtmlDialog then you can use web inspector to test the js independent of ruby…

isNaN(x1.value) will always be false as it’s a string…

x2.checked and x3.checked is what you really need…

you should also research when and why to use a radio v a checkbox as there is an expectation from the user for each type…

basically there should always be more than one radio as they imply a choice i.e. A or B…

checkboxes imply additional options i.e. A + B + C…

for radio’s you only need which ‘one’ is ‘checked’, but checkboxes you test all…

john

hello john
yes i do the test with alert and i find there is a probleme with if…

here’s an old one I posted on SketchUcation c:2013…

it may help…

def js_2_ruby

    dlg = UI::WebDialog.new("optionsDialog", false, "tlDlg", 300, 250, 150, 150, false)

    # the html for structure needs values and names in specific groups for the js to work for radio buttons and or checkboxes.

    html =<<HTML
    <html>
    <title>Web Form in SU</title>
    <head>
    <script>
    function js2ruby() {
    window.location='skp:js2ruby';
    }

    function radio(chk) {
        try {
        exists = document.getElementById(chk.name);
        exists.id = exists.value;}
        catch(err){}
        finally {
        if (chk.checked === true)
         chk.id = chk.name;}
    }

    function validate(chk) {
        if (chk.checked === true)
         chk.value = chk.name;
        else chk.value = chk.title;
    }
    </script>
<style></style>

        </head>
    <body>

    <h1>Send to ruby</h1>

    <form name="f1" id="f1">
        A Greeting to:
        <input type="text" name="greet" id="add2array1" placeholder=" to all fine gentlemen "><br/>
        Your Name:
        <input type="text " name="name " id='add2array2';" placeholder="John">
        <br />
        Your Order:
        <br />
        <input type="radio" name="add2array3" id="Pizza" value="Pizza" onclick='return radio(Pizza);'>Pizza
        <br />
        <input type="radio" name="add2array3" id="Hotdogs" value="Hotdogs" onclick='return radio(Hotdogs);'>Hotdogs
        <br/>
        <input type="checkbox" name="with sauce" id="add2array4" title="without sauce"  value="" onClick='return validate(add2array4);'>with "Tomato" Sauce?
        <br />
        <br />
        Send to Ruby:
        <input type="button" value="Submit" onClick="js2ruby();">
    </form>
     </body>
    </html>
HTML

    @html = html

    # the gist: make an array
    @tl = []

    # get 'user replys' from the webdialog,
    dlg.add_action_callback("js2ruby") {|d,_|
    # need to hard code number range to match html...
    (1..4).each{ |i| tl = d.get_element_value("add2array#{i}")
    # then add a placeholder for missing values, I like to be obvious...
    tl = "missing value" if not tl.length > 0
    # then push the full range into the array...
    @tl << tl
    }
    # if only used once per session, you could use @tl[0..3], but just incase, user make a change...
    UI.messagebox("    Greetings to #{@tl[-4]}\n   from #{@tl[-3]}\n  #{@tl[-2]} #{@tl[-1]}")
    }
    # then set_html or file/url if separate...
    dlg.set_html html
    if( (RUBY_PLATFORM =~ /darwin/i) )
    dlg.show_modal
    else
    dlg.show
    end #if

end # def js_2_ruby

# to run
js_2_ruby

hello everyone, I have a little problem, I separated the code of an HTML form into three files, a java, an html and the other ruby, except that I can not bind them, especially at the level of “window.location = \ 'skp: form2 @ ' + arg;” so do I have to put the html file name instead of form2 or something else, thanks

Read the docs, read the error messages. Use HtmlDialog because it has debug tools where you can get the precise error messages. This is better than developing blindly.


Does your HTML file load the JavaScript (!= Java) file? It should have a <script src="./relative/path/to.js"></script> tag.

The purpose of window.location = 'skp:form2@' + arg; (without space around the colon) is to communicate to the Ruby API which Ruby callback to call. That means there must be a WebDialog callback registered with the name “form2”. It does not have any other meaning. Especially should does it neither refer to a JavaScript function nor to an id of an HTMLElement.

You could also test the HTML and JavaScript in a normal web browser (e.g. Firefox) and open the develper tools (ctrlshiftI). This way you should really be able to observe what your JavaScript does and be sure that it works at all. Since the browser does not know the skp: protocol, you can replace it with console.log('skp:form2@' + arg)

hi Aerilius
, the code works well and I have no worries between java and html, I’ve been warning every step to see or miss, so I noticed that the problem is at the level from the line, "window.location …"so I would like to know if there is no specific name to put

Do you have in your Ruby code something like this: (with the exact name that you use between skp: and @)

dialog.add_action_callback('form2') { |dlg, param|
  # Add a rescue clause so that you know when your Ruby callback has an error.
  begin
  # ...
  rescue => e
    puts(e.message)
    puts(e.backtrace.join($/))
  end
}

hello
yes the same thing , i will try again

I will show you my three files … like that, it will be clearer
file ruby

require 'sketchup.rb'
require_relative 'ruby/plugin.rb'
#require_relative 'ruby/observer/entities_observer'
#require_relative 'observer/materiels_observer'

module Heron
  module Heron_rangebox
  
  
  
  
  
  
  
  
  

  def self.run()
### run the code here
  UI.messagebox('créer un projet')
   
  end
  
  def self.parametredlg
  
  
  
  dlg_html = Sketchup.find_support_file "Heron_rangebox/html/formulaire2.html", "Plugins" 
  

  
creation_dialog=UI::HtmlDialog.new(
  	{
:dialog_title => "Création Projet ",
:preferences_key => "com.sample.plugin",
:scrollable => true,
:resizable => true,
:width => 600,
:height => 400,
:left => 100,
:top => 100,
:min_width => 730,
:min_height => 620,
:max_width =>730,
:max_height => 620,
:style => UI::HtmlDialog::STYLE_DIALOG
})





creation_dialog.set_file( dlg_html)

creation_dialog.add_action_callback("form2") {|dialog, arg| 

begin
# ...
rescue => e
  puts(e.message)
  puts(e.backtrace.join($/))
end


#arr= arg.to_s

#UI.messagebox(arr)



}
# Display the dialog box
if RUBY_PLATFORM.index  "drawin"  
creation_dialog.show_modal 
else  
creation_dialog.show 
end


  	

  
  	
  	
  	
  	
  	
  
  
  #creation_dossier.set_file path
  
  #creation_dossier.add_action_callback("dlg_html") {|d, arg| 
  # arr= arg.to_s

       #   UI.messagebox(arr)
  #}
  
       #if RUBY_PLATFORM.index  "drawin"  
          #creation_dossier.show_modal 
      # else  
          #creation_dossier.show 
     #  end
  
  
  
  end

  
  unless file_loaded?(__FILE__)

    # Setup Menuu
    
    menu = UI.menu
    
    submenu = menu.add_submenu('Boite de rangement de dessin ')
  

    #(plugin.get_i18n_string( "    "  ))
    	  item_array= ["Créer Nouveau Dessin ", "Ouvrir Un Dessin "]

  			def hash(i)
  			hash = {item_array(i) => msg(i) }
    
    
  			end 
    
  			def self.choix
  			# Default code, use or delete...
  			mod = Sketchup.active_model # Open model
  			entities = mod.entities # All entities in model	  
  			number = entities.count
  			
  				if number==0
  				filepath = UI.openpanel("Open SKP File", "c:/", " .skp")
  				else 
  	
    
    
    
    
    
    
  				fileactuel= UI.messagebox("Voulez vous enregistrer le projet actuel", MB_YESNOCANCEL)
  						if fileactuel==IDYES
    
  						path_to_save_to = UI.savepanel("","..//folder","file.png||*.stl||*.stlb|")
  						UI.messagebox(" toujours je suis à l'interieur de block IDYES")
  						else
  							if fileactuel==IDNO
  							secondrespond=UI.messagebox("êtes-vous sûre de quitter sans vouloir sauvegarder le projet,à défaut le projet sera complètement détruit",MB_YESNO)
  								if secondrespond==IDNO 
  								UI.messagebox ("retour au case de départ") 
  								else
  								UI.messagebox(" vous avez choisi de ne pas sauvegarder , tout le projet sera detruit block1")
  			   
  								end 
  			
  							else 
  							UI.messagebox("retour au projet")
  							end 
  						end 
  
  				end 
  			return if filepath.nil? # user cancelled
  			#UI.messagebox("return if filepath.nil?")
  			mod = Sketchup::active_model
  			#UI.messagebox("mod = Sketchup::active_model")
  			cdef = mod.definitions.load(filepath)
  			#UI.messagebox("cdef = mod.definitions.load(filepath)")
  			return unless cdef # good practice
  			# could be "next unless cdef" inside a loop
  			#UI.messagebox("return unless cdef")

  			point = Geom::Point3d::new( 0, 0, 0 ) # loaded from external file
  			#UI.messagebox("point = Geom::Point3d::new( 10, 10, 0 )")
  			cinst = mod.active_entities.add_instance(
  				cdef,
  				Geom::Transformation::new( point )
  			)
  			UI.messagebox("cinst = mod.active_entities.add_instance(
  				cdef,
  				Geom::Transformation::new( point )
  			)")
    
    
    
    
    
  			#ent =Sketchup.active_model.entities # Open model
    
  			#ent.load filepath
    
    
    
    
  			#UI.messagebox("étape déroulé avec succés")
    
  			cinst.explode
  			#UI.messagebox("image éclaté")
  			end 
    
   
    
    
              for i in (0.. 1)
  		
  			submenu.add_item(item_array[i])  { UI.messagebox i;}
    
  			end 
    
    
    
  			#submenu.add_item('tab.paramètres.title')     {  self.parametredlg
  			#UI.messagebox('réglages paramètres')
  			#}
  

  			# Setup Toolbar
    
  			toolbar = UI::Toolbar.new('Heronrangement')
    
   
  			cmd1 = UI::Command.new('Heronrangement')  { self.parametredlg;
  			#UI.messagebox('réglages paramètres') 
    
   }#{ UI.messagebox('Créer Un Nouveau Dessin') }
   
    cmd2 = UI::Command.new('Heronrangement')  { self.choix;
    }#UI.messagebox('Ouvrir un Dessin')
   
  
    
    cmd1.small_icon = 'img/ik1.png'
    cmd1.large_icon = 'img/ik1.png'
    cmd2.small_icon = 'img/ik2.png'
    cmd2.large_icon = 'img/ik2.png'
    
    
    
    
    cmd1.tooltip = ('	Créer un nouveau dessin')
    cmd2.tooltip = ('Ouvrir un dessin existant ')
   
    
    
    
    
    
    cmd1.status_bar_text = ('Pour créer un nouveau dessin ')
    cmd2.status_bar_text = ('Pour ouvrir un dessin existant ')
    
    #cmd.menu_text = plugin.get_i18n_string('core.toolbar.command')
    toolbar = toolbar.add_item(cmd1)
    toolbar = toolbar.add_item(cmd2)
   
    
    toolbar.show

    file_loaded(__FILE__)
  
    
  end 
    
end
end 

file javascript

function sendData()        
{ 

alert("begin step")        
 
var ids = new Array ("dt","soc","nompr","np","adres","cp","vil","pys","mou","mail1","moe","mail2","hti","nbetg","lati","longi","ssol","nbessol");            
var arg = "" ; var entry = "" ; var valid = true ;            
// Iterate through the text boxes to form output argument   
alert("step2")


for (i in ids)  {   

			entry = document.getElementById(ids[i]).value
			arg = arg + entry + " ,  "; 
            
alert(arg)


  }
  
  window.location = \'skp:form2@\' + arg ; 
  
  
  
}

file html

<html name="dlg_html">
    <head>
        <meta charset="utf-8">
       <title> FORMULAIRE CREATION PROJET </title>
       <link rel="stylesheet" type="text/css" href="../css/formulaire2.css" media="all" />
	   
	 <script type="text/javascript" src="../js/scriptformulaire2.js">         
        
</script>     
	
    </head>
 <body> 
 <fieldset id="fieldset4">
 <legend id="legend"> 
 Paramètres du Projet: </legend>
<form> 
 <!-- Location of the first vertex -->      
   
 <fieldset id="fieldset1">
 <legend id="legend"> Données Dossier </legend>
 <div id="blocdiv1">
 <div id="div1">
 <label for="dt"> Date </label> <input type="date" id="dt" value="20/12/2015" required />   
</div>
<div id="div2"> 
 <label for="soc"> Société </label> <input type="text" id="soc" value="EFEMI" required /> 
 </div>
 <div id="div3">
 <label for="nompr"> Nom/Pénom </label> <input type="text" id="nompr" value="Mr.LOUZA FRED" required /> 
</div> 
</div>
   </fieldset>
   
   <fieldset id="fieldset2">
   <legend id="legend">Données Projet</legend>
   <label for="np">Nom Du Projet: </label>
   <input type="text" id="np" placeholder="résidence gammarth" value="france" required></br>
   <label for="adres" > Adresse Du Projet: </label>
   <textarea type="text" id="adres" placeholder="15 rue de pascal" value ="" required></textarea></br>
   <label for="cp" > Code Postal:</label>
   <input type="text" id="cp" placeholder="75020" value="" required></br>
   <label for="vil">Ville </label>
   <input type="text" id="vil" placeholder="Paris" value="" required></br>
   <label for="pys" >Pays </label>
   <input type="text" id="pys" placeholder="France" value="" required></br>
   <label  for="mou">Maitre D'ouvrage </label>
   <input type="text" id="mou" placeholder="MOU" value=""></br>
   <label for="mail1"> Email </label>
   <input type="email" id="mail1" placeholder="mou@mou.com" value="" ></br>
   <label for="moe">Maitre D'oeuvre </label> 
   <input type="text" id="moe" placeholder="MOE" value="" ></br>
   <label for="mail2">Email </label>
   <input type="email" id="mail2" placeholder="moe@moe.com" value="" ></br>
  
   
   </fieldset >
   
    <fieldset id="fieldset3" >
   <legend id="legend"> Données Immeuble </legend>
   <label for="hti">Hauteur D'immeuble:</label>
   <input type="number" id="hti" placeholder="15" value="" required></br>
   <label for="nbetg">Nombre D'étage </label>
   <input type="number" id="nbetg" placeholder="2" value="" required></br>
   <label for="lati" >Latitude  </label>
   <input type="text" id="lati" placeholder="latitude" value="100.000"></br>
   <label for="longi" >Longitude </label>
   <input type="text" id="longi" placeholder="longitude" value="100.000"></br>
   <label for="ssol" > Sous-sol </label>
   <input type="text" id="ssol" placeholder="OUI/NON" value="OUI"></br>
   <label for="nbessol">Nombre De Niveau Sous-sol </label>
   <input type="number" id="nbessol" placeholder="1" value="1"></br>
   
    
    </fieldset>
 <br /><br />      
 <!-- Send points to JavaScript -->
 <div id="div4">
  <input type="button" style= "color:white;background-color:green" value="Annuler" accesskey="a" onclick="self.close()";/>
  <input type="button" style ="color:white;background-color:green" onclick="sendData();" accesskey="c" value="Enregistrer" /> 
</div> 
 </form>
 </fieldset>
 </body> 
 </html>

you are using javascript and the common short name is js

java is a completely unrelated language that you are not using…

some plugins do use java, but that requires the user to instal an additional program…

please edit your post, to show you now understand that it is both annoying and confusing to use the wrong name for the code language…

john

1 Like

hello every body,
i have a great probleme with the code, when i collect the files in one file and i test them on ruby consol every thing works good, but when i make a separatly files, the code don’t work, i do not know what’s the problem, there is someone can help me please?