jeudi 4 mars 2021

CheckBox React Native com api rest checando todos ao inves de selecionado [closed]

Estou com problema na seleçao de um array com checkbox, ele retorna o index certo, marca o selecionado, só que seleciona todos e o restante selecionado fica com o value={false}

o código é esse

function onChecked(id){
    const data = adc
    const index = data.findIndex(x => x._id === id)
    data[index].checked = !data[index].checked
    
    setCheck(data[index].checked)

    alert(index)
}
...

<TouchableOpacity key={a._id} onPress={() => {this.onChecked(a._id)}} style=>
     <CheckBox value={check} onValueChange={() => {onChecked(a._id)}}/>
</TouchableOpacity>

os valores retornam normal, o problema só é que ao inves de marcar só o selecionado ele marca todos, mas os valores continuam como false nos que não foram marcados




Checkbox in the woocommerce product loop

I need to create a checkbox in the product loop, where the user can check that they want to request a certificate. There is already a text field, where you can set the size of the product, there is also code for it that works. It also works on the product side. However, in the product loop, the value of the check box is always taken, but it should only be checked if the user has checked it.

function add_name_on_certificate_field() {
echo '<table class="certificate" cellspacing="0">
      <tbody>
          <tr>
             <td class="value">
              Certificate: <input type="checkbox" name="name_on_certificate" value="certificate" "/>                      
             </td>
         </tr>                               
      </tbody>
  </table>';}

add_action( 'woocommerce_before_add_to_cart_button', 'add_name_on_certificate_field'); 


 function save_name_on_certificate_field( $cart_item_data, $product_id ) {
    if( isset( $_REQUEST['name_on_certificate'] ) ) {
       $cart_item_data[ 'name_on_certificate' ] = $_REQUEST['name_on_certificate'];
       $cart_item_data['unique_key'] = md5( microtime().rand() );
    }
  return $cart_item_data;
}
add_action( 'woocommerce_add_cart_item_data', 'save_name_on_certificate_field', 10, 2 ); code here


function render_meta_on_cart_and_checkout2( $cart_data, $cart_item = null ) {
    $custom_items = array();
    if( !empty( $cart_data ) ) {
        $custom_items = $cart_data;
    }
    if( isset( $cart_item['name_on_certificate'] ) ) {
       $custom_items[] = array( "name" => 'Certificate', "value" => 
        $cart_item['name_on_certificate']);
    }
    return $custom_items;
 }
 add_filter( 'woocommerce_get_item_data', 'render_meta_on_cart_and_checkout2', 10, 2 );

  function certificate_order_meta_handler( $item_id, $values, $cart_item_key ) {
      if( isset( $values['name_on_certificate'] ) ) {
       wc_add_order_item_meta( $item_id, "name_on_certificate", $values['name_on_certificate']);
      }
  }
  add_action( 'woocommerce_add_order_item_meta', 'certificate_order_meta_handler', 1, 3 );


 function add_custom_fields_on_product_listing2() {
      global $product;
      echo '</a><div class="sark-custom-fields-wrapper">
          <input type="checkbox" id="name_on_certificate-'. $product->id .'" value="certificate-required" /> </div>';
}
 add_action( "woocommerce_after_shop_loop_item", 'add_custom_fields_on_product_listing2', 1 );


function inject_custom_field_script2() { ?>
     <script type="text/javascript">       
       jQuery(document).on("adding_to_cart", function( e, btn, data ){
        data["name_on_certificate"] = jQuery("#name_on_certificate-" + btn.attr( "data-product_id" )).val();
     return true;
    });
  
  </script>
 <?php }
add_action( "woocommerce_after_main_content", 'inject_custom_field_script2', 1 );



React Native - How to select multiple items and display them?

I would like to display selected items, but the situation I have got is not showing images but only the backgroundColor. There is image uri in productData, so I would like to display the uri. Another issue I am having is that the CheckBox is not checked.

My code below :


const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 100,
  },
  topContainer: {
    flexDirection: 'row',
    marginHorizontal: 15,
    paddingBottom: 20,
    paddingTop: 10,
    borderBottomWidth: 0.5,
    borderColor: colors.very_light_pink,
  },
  iconWrap: {
    width: 60,
    height: 60,
    borderRadius: 6,
    backgroundColor: '#cccccc',
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: 5,
  },
  icon: {
    width: 20,
    height: 20,
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginHorizontal: 15,
    marginBottom: 15,
  },
});

const productData = [
  {
    id: 0,
    productName: 'a',
    price: 45000,
    image:
      'https://static.zara.net/photos///2021/V/0/2/p/8211/407/250/73/w/563/8211407250_2_1_1.jpg?ts=1613387641299',
  },
  {
    id: 1,
    productName: 'b',
    price: 45000,
    image:
      'https://static.zara.net/photos///2021/V/0/2/p/0526/407/707/2/w/1280/0526407707_6_1_1.jpg?ts=1610451943259',
  },
  {
    id: 2,
    productName: 'c',
    price: 129000,
    image:
      'https://static.zara.net/photos///2021/V/0/2/p/0706/442/710/2/w/563/0706442710_2_1_1.jpg?ts=1614254205907',
  },
  {
    id: 3,
    productName: 'd',
    price: 139000,
    image:
      'https://static.zara.net/photos///2021/V/0/2/p/0706/431/446/2/w/563/0706431446_2_1_1.jpg?ts=1613386951068',
  },
  {
    id: 4,
    productName: 'e',
    price: 189000,
    image:
      'https://static.zara.net/photos///2021/V/0/2/p/4162/536/401/2/w/1280/4162536401_1_1_1.jpg?ts=1613122054256',
  },
  {
    id: 5,
    productName: 'f',
    price: 89000,
    image:
      'https://static.zara.net/photos///2021/V/0/2/p/4165/537/430/2/w/563/4165537430_1_1_1.jpg?ts=1613122064808',
  },
];

const LiveAddProducts = (props) => {
  const [productClicked, setProductClicked] = useState(null);
  const [selectedProducts, setSelectedProducts] = useState([]);

  useEffect(() => {
    if (productClicked !== null) {
      setSelectedProducts((prevState) => [
        ...prevState,
        // I believe this should be changed
        { id: prevState.length, image: productClicked },
      ]);

      setProductClicked(null);
    }
  }, [productClicked]);

  console.log(selectedProducts.image);

  return (
    <View style={[styles.container]}>
      <View style={[styles.topContainer]}>
        <TouchableOpacity style={[styles.iconWrap]}>
          <Image source={assets.live_add_icon} style={[styles.icon]} />
        </TouchableOpacity>

        {selectedProducts.map((item, index) => (
          <TouchableOpacity style={[styles.iconWrap]} key={item.id}>
            <Image source= style={[styles.icon]} />
          </TouchableOpacity>
        ))}
      </View>

      <ScrollView style=>
        {productData.map((item, index) => (
          <View style={[styles.row]}>
            <ProductsList
              price={item.price}
              image={item.image}
              productName={item.productName}
            />
            // Any problems here?
            <CheckBox
              size={20}
              onPress={() => setProductClicked(index)}
              source={
                productClicked === index
                  ? assets.icon_check_on
                  : assets.checked_off
              }
            />
          </View>
        ))}
      </ScrollView>
      <BottomButton
        btnText={'Add Items'}
        buttonStyle=
      />
    </View>
  );
};

LiveAddProducts.propTypes = {};

export default LiveAddProducts;

The image which has problems :

As you can see, I can't see the image and the CheckBox is not checked




mercredi 3 mars 2021

Listview with radio and checkbox check and uncheck android

I want make a listview which have five item. every item in first 3 are just radio with checkbox are GONE and in list 2 checkbox and radio are GONE. i want when click on radio other 2 radio are uncheck and checkbox remain same if check or uncheck remain same and when i click on check box if checkbox already check that shoud be uncheck but all other radio and checkbox not change they should be remain same and if i check on other checkbox it also works alone please help me.

i have issue is that when i click on radio other check box shoud bhe change but i not want to change it shoud be wor[whats][1]

ListAdapter

public class Listadapter extends ArrayAdapter {

private final Activity context;
private final String[] maintitle;
private final String[] describe;
private final Integer[] imgid;
RadioButton rbut;
CheckBox cBox1;
int checkBox=2;
ArrayList<String> arrayList2;
ArrayList<Integer> checkList;
int selectedRbtPos=-1;

Boolean checkboxflag=false;

// boolean[] itemChecked;

public Listadapter(Activity context, String[] maintitle, String[] describe, Integer[] imgid,ArrayList<String>arrayList2) {
    super(context,R.layout.list_item,maintitle);
    this.context = context;
    this.maintitle=maintitle;
    this.describe=describe;
    this.imgid=imgid;
    this.arrayList2=arrayList2;
    checkList = new ArrayList<Integer>();

// itemChecked = new boolean[packageList.size()]; }

public View getView(int position,View view,ViewGroup parent){

    LayoutInflater inflater=context.getLayoutInflater();
    View rowView=inflater.inflate(R.layout.list_item, null,true);

    TextView titleText = (TextView) rowView.findViewById(R.id.textView1);
    ImageView imageView = (ImageView) rowView.findViewById(R.id.imgid);
    TextView describeText = (TextView) rowView.findViewById(R.id.textView2);
    RadioButton rbut=rowView.findViewById(R.id.rbut);
    cBox1=rowView.findViewById(R.id.cBox1);

    titleText.setText(maintitle[position]);
    imageView.setImageResource(imgid[position]);
    describeText.setText(describe[position]);

    if (selectedRbtPos==position){
        rbut.setChecked(true);
        titleText.setTag(maintitle[selectedRbtPos]);
        String b = titleText.getTag().toString();
        arrayList2.add(b);
    }
    else
        if (position<2)
        rbut.setChecked(false);
       if( cBox1.isChecked())
           cBox1.setChecked(true);
       else
           cBox1.setChecked(false);


    if (position<2)
        cBox1.setVisibility(View.GONE);
    if (position>1)
        rbut.setVisibility(View.GONE);
    cBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            checkBox = position;
        }
    });

    rbut.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            selectedRbtPos = position;

            notifyDataSetChanged();
        }
    });

    return rowView;

};

}




Add extra checkboxes in Woocommerce user register form and saving / showing if are checked in the backend as user extra data

I would like to show in the backend, when seeing the user detail if the checkboxes were selected when the user was created, here is the code that helped me to implement the extra checkboxes in the register form.

function woocommerce_edit_my_account_page() {
    return apply_filters( 'woocommerce_forms_field', array(
        'woocommerce_my_account_page' => array(
            'type'        => 'checkbox',
            'label'       => __( 'Soy mayor de 18'),
            'required'    => true,
        ),
        array(
            'type'        => 'checkbox',
            'label'       => __( 'Le doy permiso de usar mis datos'),
            'required'    => true,
        ),
    ) );
}
function edit_my_account_page_woocommerce() {
    $fields = woocommerce_edit_my_account_page();
    foreach ( $fields as $key => $field_args ) {
        woocommerce_form_field( $key, $field_args );
    }
}
add_action( 'woocommerce_register_form', 'edit_my_account_page_woocommerce', 15 );



How to post SQL values into checkboxes

First of all, my question might be a duplicate question to this one: Need html checkbox to be checked by mysql result but I do not understand the answer - the op didn't post any code and I don't see how to fit the suggested code into my case because I need to get the values from SQL (?).

Here all the data: I have an HTML form with checkboxes, which stores the values as for checked as "1" and unchecked as "0" into an SQL database on submit of the form. Now I want to make it so that it (on page load) pulls data from database and populates the form's checkboxes when the same user comes back to the page. (I know my code is faulty in some places, I still need to resolve quite some things on this project) for right now, what I want to solve is to get the SQL to output the result to existing HTML checkboxes (not create new checkboxes or new HTML form).

Note: my HTML form and my php form are in two separate files and they cannot be merged (I don't know if that makes a difference).

All checkboxes in the form are empty by default. I am using Ajax in my form so that on pageload the userid is passed to a php file which then runs the SQL Query to pull up "1" if the checkbox should be checked and "0" if it should be left unchecked.

Here the piece of HTML which is relevant to the case:

<input type=text id="userid" name="userid" value="">
        </div>                     
        <div class="grid">
            <div>
                <div class="grid-item">
                <img src="image.png" alt=""></div>
                <div class="grid-item-title">
                <h2>Title</h2>
                </div>
                <div class="grid-item">
                <p>
               <input type="hidden" name="owns[item1]" value="0"><input type="checkbox" onclick="this.previousSibling.value=1-this.previousSibling.value">I own this<br>
                </p></div>
            </div>
            <div>
                <div class="grid-item">
                <img src="image.png" alt=""></div>
                <div class="grid-item-title">
                <h2>Title 2</h2>
                </div>
                <div class="grid-item">
                <p>
                <input type="hidden" name="owns[item2]" value="0"><input type="checkbox" onclick="this.previousSibling.value=1-this.previousSibling.value">I own this<br>
                </p></div>
            </div>

This is the Ajax code I am using:

document.addEventListener("DOMContentLoaded", function myFunction() {
    var x = 3 //replace with user ID
 
    $.ajax({
    url: 'libraryRequest.php',
    method: "post",
    data: {"userid": x }, // sends id to PHP 
    dataType: "html",
    async: false,
    success: function(data){
        $('#content').html(data); // currently this overwrites all HTML on the page... 
    },
    error: function (xhr, ajaxOptions, thrownError) {
        var errorMsg = 'Ajax request failed: ' + xhr.responseText;
        $('#content').html(errorMsg); // currently this overwrites all HTML on the page... 
      }
})
});

And this is the PHP code I managed to put together sofar:

$userid = 0;
$userid = $_POST['userid'];
if ($userid != 0) {  //only execute if there is a user id
    $userquery = "SELECT * FROM libraryG WHERE userid =$userid"; //find if userid exists
    $result = mysqli_query($con, $userquery);
    if(mysqli_num_rows($result)>0) { //if user id exists run this code to pull the data
        $sqlupdate = "SELECT * FROM libraryG WHERE userid = $userid";
        mysqli_query($con, $sqlupdate); 
        
        if ($result->num_rows > 0) {
        while($row = $result->fetch_row()) {
        echo $row[1]; // these echo "1" or "0" correctly but I'm missing the link to the HTML
        echo $row[2]; // also this should be an array/loop because eventually it will be many 
        echo $row[3];
        echo $row[4];
        echo $row[5];
        }

    } //if user id doesn't exist in db or there is no user id - do nothing 

    } 

Each checkbox value is stored in a separate column in SQL.

I have been on this for hours now but in most cases the similar questions I found are explaining solutions for C# or ASP which I have never used and being kinda new in everything I try to avoid those things I don't know anything about if there is a way to do it otherwise.




I want to sum numbers when a checkbox is checked in javascript

I want to sum the numbers and print them out in the span, i tried with innerHTML but as it is a string i can't, i tried parseInt, parseFloat, Number and nothing. For all the checkbox checked i want the sum of it's values into the span and those who are not checked i don't want them to get summ in the span

(i reduced the table and a lot of numbers because it's so long for putting it in here, so imagine that i want to sum a lot of total numbers)

const offersCheckbox = document.querySelectorAll("#checkbox-offers");
const recalculateText = document.querySelector(".recalculate-text");
const checkboxTotal = document.querySelectorAll("#checkbox-total");
let total = 0;

for (let i = 0; i < offersCheckbox.length; i++) {
  offersCheckbox[i].addEventListener("click", (e) => {
    if (offersCheckbox[i].checked === true) {
      recalculateText.innerHTML = "recalculate invoice total";
    } else {
      recalculateText.innerHTML = "";
    }
  });
}
<table>
  <tr>
    <tr>
      <td>
        <input type="checkbox" name="checkbox" id="checkbox-offers" value="2,434.38" />
        <td>
          <div class="price-container text-bold" id="checkbox-total">
            <b>$</b>2,434.38
          </div>
        </td>
    </tr>

    <tr>
      <td>
        <input type="checkbox" name="checkbox" id="checkbox-offers" value="76.69" />
      </td>
      <td>
        <div class="price-container text-bold" id="checkbox-total">
          <b>$</b>76.69
        </div>
      </td>
    </tr>
</table>

<span class="recalculate-text text-right text-underline"></span>